agora inbox for [email protected]help / color / mirror / Atom feed
[PATCH] Teach REPACK to upgrade its lock safely. 188+ 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; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH] Teach REPACK to upgrade its lock safely. @ 2026-04-14 09:59 Antonin Houska <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw) REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to AccessExclusiveLock at the end of table processing. If another session, which already has a non-conflicting lock on the table, tried to get SUEL too, it would end up in a deadlock with REPACK. Such situation does not hurt as long as the deadlock detector choses to terminate the other session, but it's possible that it terminates REPACK. A lot of REPACK's work would be wasted this way. This patch checks for such situation, and if the other session tries to get the SUEL, it receives a deadlock report before it actually starts waiting. Please note that the other session can safely run VACUUM w/o receiving the deadlock report. The point is that VACUUM cannot run in a transaction block, so the session cannot have any other lock when trying to get SUEL on the table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and then it can start. --- src/backend/commands/repack.c | 25 +++++++- src/backend/storage/lmgr/deadlock.c | 10 ++-- src/backend/storage/lmgr/lock.c | 30 ++++++++++ src/backend/storage/lmgr/proc.c | 55 ++++++++++++++++- src/include/storage/lock.h | 5 +- src/include/storage/proc.h | 6 +- .../injection_points/expected/repack.out | 59 ++++++++++++++++++- .../injection_points/specs/repack.spec | 29 +++++++++ 8 files changed, 209 insertions(+), 10 deletions(-) diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 58e3867246f..e9193067666 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel) * to understand and we don't lose any functionality. */ PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)"); + + /* + * Also set the PROC_IN_CONCURRENT_REPACK flag. This makes the lock + * manager cause anyone that would conflict with us to error out. + * It's important to set this flag ahead of actually locking the + * relation; it won't of course affect anyone until we do have a lock + * that others can conflict with. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); } /* @@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock); /* - * Tuples and pages of the old heap will be gone, but the heap will stay. + * Now that we have all access-exclusive locks on all relations, we no + * longer want other processes to error out when trying to acquire a + * conflicting lock. Therefore, unset our flag. + */ + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); + MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK; + ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; + LWLockRelease(ProcArrayLock); + + /* + * Tuples and pages of the old heap will be gone, but the heap itself will + * stay. */ TransferPredicateLocksToHeapRelation(OldHeap); foreach_ptr(RelationData, index, indexrels) diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index b8962d875b6..3772a7aa3df 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -1146,8 +1146,10 @@ DeadLockReport(void) void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2) + LOCK *lock, /* XXX Only lockmode? */ + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2) { DEADLOCK_INFO *info = &deadlockDetails[0]; @@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1, info->lockmode = lockmode; info->pid = proc1->pid; info++; - info->locktag = proc2->waitLock->tag; - info->lockmode = proc2->waitLockMode; + info->locktag = *locktag2; + info->lockmode = lockmode2; info->pid = proc2->pid; nDeadlockDetails = 2; } diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index c221fe96889..44aa2ca26a7 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag, return false; } +/* + * HaveRelLock -- test whether the current backend has a fast path lock on + * the relation in any mode. + */ +bool +HaveFastPathLock(Oid relid) +{ + uint32 group = FAST_PATH_REL_GROUP(relid); + bool result = false; + + LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED); + for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++) + { + uint32 f = FAST_PATH_SLOT(group, i); + uint32 lockmask; + + if (relid != MyProc->fpRelId[f]) + continue; + lockmask = FAST_PATH_GET_BITS(MyProc, f); + if (lockmask) + { + result = true; + break; + } + } + LWLockRelease(&MyProc->fpInfoLock); + + return result; +} + #ifdef USE_ASSERT_CHECKING /* * GetLockMethodLocalHash -- return the hash of local locks, for modules that diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 1ac25068d62..3d47b1284a3 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) LOCKMASK myHeldLocks; bool early_deadlock = false; PGPROC *leader = MyProc->lockGroupLeader; + bool check_repack = false; Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE)); @@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) } } + /* + * If I am already holding this lock (in any mode) and trying to get + * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is + * already holding ShareUpdateExclusiveLock. The problem is if that by + * trying to upgrade the lock to AccessExclusiveLock it would get into a + * deadlock with us. + */ + if (lock->tag.locktag_type == LOCKTAG_RELATION && + lock->tag.locktag_field1 == MyDatabaseId && + lockmode >= ShareUpdateExclusiveLock) + { + if (myHeldLocks > 0 || + HaveFastPathLock(lock->tag.locktag_field2)) + check_repack = true; + } + if (check_repack) + { + dlist_iter iter; + + dlist_foreach(iter, &lock->procLocks) + { + PROCLOCK *otherproclock; + PGPROC *otherproc; + + otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur); + otherproc = otherproclock->tag.myProc; + if (otherproc != MyProc && + otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK) + { + LOCKMASK repackmask = otherproclock->holdMask; + + /* + * Is REPACK already holding ShareUpdateExclusiveLock? + */ + if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0) + { + /* + * There should be no more than one REPACK working on + * particular table, so let's error out. + */ + RememberSimpleDeadLock(MyProc, lockmode, lock, + otherproc, + ShareUpdateExclusiveLock, + &otherproclock->tag.myLock->tag); + return PROC_WAIT_STATUS_ERROR; + } + } + } + } + /* * Determine where to add myself in the wait queue. * @@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait) * a flag to check below, and break out of loop. Also, * record deadlock info for later message. */ - RememberSimpleDeadLock(MyProc, lockmode, lock, proc); + RememberSimpleDeadLock(MyProc, lockmode, lock, proc, + proc->waitLockMode, + &proc->waitLock->tag); early_deadlock = true; break; } diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index ee3cb1dc203..85804d61ce9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks); extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger); +extern bool HaveFastPathLock(Oid relid); #ifdef USE_ASSERT_CHECKING extern HTAB *GetLockMethodLocalHash(void); #endif @@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, - PGPROC *proc2); + PGPROC *proc2, + LOCKMODE lockmode2, + LOCKTAG *locktag2); extern void InitDeadLockChecking(void); extern int LockWaiterCount(const LOCKTAG *locktag); diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 3e1d1fad5f9..76c6bb44251 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -70,10 +70,12 @@ struct XidCache #define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be * included in vacuum horizons * in all databases */ +#define PROC_IN_CONCURRENT_REPACK 0x40 /* REPACK (CONCURRENTLY) */ -/* flags reset at EOXact */ +/* flags reset at EOXact. A bit of a misnomer ... */ #define PROC_VACUUM_STATE_MASK \ - (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND) + (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \ + PROC_IN_CONCURRENT_REPACK) /* * Xmin-related flags. Make sure any flags that affect how the process' Xmin diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out index b575e9052ee..960044776f4 100644 --- a/src/test/modules/injection_points/expected/repack.out +++ b/src/test/modules/injection_points/expected/repack.out @@ -1,4 +1,4 @@ -Parsed test spec with 2 sessions +Parsed test spec with 3 sessions starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1 injection_points_attach @@ -111,3 +111,60 @@ injection_points_detach (1 row) + +starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only +injection_points_attach +----------------------- + +(1 row) + +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 1 +(1 row) + +step wait_before_lock: + REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey; + <waiting ...> +step lock3: + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; + +i|j +-+- +1|1 +(1 row) + +ERROR: deadlock detected +step wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step wait_before_lock: <... completed> +step check1_relnode_only: + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; + +count +----- + 2 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec index d727a9b056b..5ffcb558718 100644 --- a/src/test/modules/injection_points/specs/repack.spec +++ b/src/test/modules/injection_points/specs/repack.spec @@ -55,6 +55,13 @@ step check1 FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j) WHERE d1.i ISNULL OR d2.i ISNULL; } +step check1_relnode_only +{ + INSERT INTO relfilenodes(node) + SELECT relfilenode FROM pg_class WHERE relname='repack_test'; + + SELECT count(DISTINCT node) FROM relfilenodes; +} teardown { SELECT injection_points_detach('repack-concurrently-before-lock'); @@ -129,6 +136,20 @@ step wakeup_before_lock SELECT injection_points_wakeup('repack-concurrently-before-lock'); } +session s3 +# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already +# holding it and before it tries to upgrade it to AccessExclusiveLock. Since +# this session is already holding another lock no the table, REPACK cannot +# resolve the problem by getting ahead in the wait queue. The solution is that +# the LOCK TABLE triggers a deadlock report. The deadlock does not actually +# take place, but it would if this session started to wait. +step lock3 +{ + BEGIN; + SELECT * FROM repack_test ORDER BY i LIMIT 1; + LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE; +} + # Test if data changes introduced while one session is performing REPACK # CONCURRENTLY find their way into the table. permutation @@ -140,3 +161,11 @@ permutation check2 wakeup_before_lock check1 + +# See 'lock3' above. We check relnodes to make sure that REPACK finished. +permutation + check1_relnode_only + wait_before_lock + lock3 + wakeup_before_lock + check1_relnode_only -- 2.47.3 --=-=-=-- ^ permalink raw reply [nested|flat] 188+ messages in thread
* [PATCH v3 1/2] Support changing a column into a stored generated column @ 2026-04-24 08:44 Alberto Piai <[email protected]> 0 siblings, 0 replies; 188+ messages in thread From: Alberto Piai @ 2026-04-24 08:44 UTC (permalink / raw) This adds an ALTER TABLE subcommand to turn a regular column into a stored generated column: ... ALTER COLUMN c ADD GENERATED ALWAYS as (expr) STORED The syntax is chosen to be similar to ... ALTER COLUMN ... ADD GENERATED ... AS IDENTITY with the difference that in this case, since we're dealing with a generated column, only ALWAYS is supported. Additionally, STORED must always be specified. This new operation fits together with SET EXPRESSION and DROP EXPRESSION. Phase 2 happens in the same pass as the former, in order to run the cleanup code in ATPostAlterTypeCleanup, without which for example we would not re-check constraints when rewriting the table. Partitioning/inheritance is supported in the same way as DROP EXPRESSION: it is allowed to change the whole inheritace tree to/from a generated column at once; it is forbidden to change the parent table ONLY and it is forbidden to change a partition directly. See 8bf6ec3ba3a44448817af47a080587f3b71bee08 and the associated discussion. There is one limitation: currently DROP EXPRESSION does not allow to change an inheritance tree of depth > 2. This seems like an oversight, but in order to not feature-creep this commit, this is postponed for later; it should then be fixed for both DROP EXPRESSION and this new command. This is mostly useful as a first step to be able to add a stored generated column without rewriting the table under an exclusive lock. For ease of review, the operation as of this commit always rewrites the contents of the column using the new generated expression. --- src/backend/commands/tablecmds.c | 186 +++++++++++++++++- src/backend/parser/gram.y | 31 +++ src/include/nodes/parsenodes.h | 1 + .../test_ddl_deparse/test_ddl_deparse.c | 3 + src/test/regress/expected/alter_table.out | 126 ++++++++++++ src/test/regress/sql/alter_table.sql | 76 +++++++ 6 files changed, 422 insertions(+), 1 deletion(-) diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index d8d7969bf30..aa54c629f8b 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -783,6 +783,14 @@ static void ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation static void ATExecSplitPartition(List **wqueue, AlteredTableInfo *tab, Relation rel, PartitionCmd *cmd, AlterTableUtilityContext *context); +static void ATPrepAddGeneratedAsExprStored(Relation rel, + AlterTableCmd *cmd, + bool recurse, bool recursing, + LOCKMODE lockmode); +static ObjectAddress ATExecAddGeneratedAsExprStored(AlteredTableInfo *tab, + Relation rel, + const char *colName, + Constraint *def); static List *collectPartitionIndexExtDeps(List *partitionOids); static void applyPartitionIndexExtDeps(Oid newPartOid, List *extDepState); static void freePartitionIndexExtDeps(List *extDepState); @@ -4769,6 +4777,7 @@ AlterTableGetLockLevel(List *cmds) case AT_AddIdentity: case AT_DropIdentity: case AT_SetIdentity: + case AT_AddGeneratedAsExprStored: case AT_SetExpression: case AT_DropExpression: case AT_SetCompression: @@ -5093,6 +5102,13 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); pass = AT_PASS_SET_EXPRESSION; break; + case AT_AddGeneratedAsExprStored: + ATSimplePermissions(cmd->subtype, rel, + ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); + ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context); + ATPrepAddGeneratedAsExprStored(rel, cmd, recurse, recursing, lockmode); + pass = AT_PASS_SET_EXPRESSION; + break; case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */ ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE); @@ -5487,6 +5503,12 @@ ATExecCmd(List **wqueue, AlteredTableInfo *tab, case AT_SetExpression: address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode); break; + case AT_AddGeneratedAsExprStored: + Assert(IsA(cmd->def, Constraint)); + address = ATExecAddGeneratedAsExprStored(tab, rel, + cmd->name, + (Constraint *) cmd->def); + break; case AT_DropExpression: address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode); break; @@ -6695,6 +6717,8 @@ alter_table_type_to_string(AlterTableType cmdtype) return "ALTER COLUMN ... SET NOT NULL"; case AT_SetExpression: return "ALTER COLUMN ... SET EXPRESSION"; + case AT_AddGeneratedAsExprStored: + return "ALTER COLUMN ... ADD GENERATED ALWAYS AS (...) STORED"; case AT_DropExpression: return "ALTER COLUMN ... DROP EXPRESSION"; case AT_SetStatistics: @@ -8851,6 +8875,164 @@ ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName, return address; } +/* + * Preparation for + * + * ALTER TABLE ALTER COLUMN ADD GENERATED ALWAYS AS expr STORED + * + * Checks whether recursion is allowed, following the same logic as ATPrepDropExpression. + */ +static void +ATPrepAddGeneratedAsExprStored(Relation rel, + AlterTableCmd *cmd, + bool recurse, bool recursing, + LOCKMODE lockmode) +{ + /* + * Reject ONLY if there are child tables. See ATPrepDropExpression. + */ + if (!recurse && + find_inheritance_children(RelationGetRelid(rel), lockmode)) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("ALTER TABLE / ADD GENERATED ALWAYS AS (expr) STORED must be applied to child tables too"))); + + /* + * Cannot change only inherited columns to be stored generated columns. + */ + if (!recursing) + { + HeapTuple tuple; + Form_pg_attribute attTup; + + tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_COLUMN), + errmsg("column \"%s\" of relation \"%s\" does not exist", + cmd->name, RelationGetRelationName(rel)))); + + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + + if (attTup->attinhcount > 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot change inherited column to be a stored generated column"))); + } +} + +/* + * ALTER TABLE ALTER COLUMN ADD GENERATED ALWAYS AS expr STORED + */ +static ObjectAddress +ATExecAddGeneratedAsExprStored(AlteredTableInfo *tab, + Relation rel, + const char *colName, + Constraint *def) +{ + HeapTuple tuple; + Form_pg_attribute attTup; + AttrNumber attnum; + ObjectAddress address; + Expr *defval; + NewColumnValue *newval; + RawColumnDefault *rawEnt; + Relation pg_attribute; + + Assert(def->raw_expr != NULL); + Assert(def->cooked_expr == NULL); + Assert(def->generated_when == ATTRIBUTE_IDENTITY_ALWAYS); + Assert(def->generated_kind == ATTRIBUTE_GENERATED_STORED); + + tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_COLUMN), + errmsg("column \"%s\" of relation \"%s\" does not exist", + colName, RelationGetRelationName(rel)))); + + attTup = (Form_pg_attribute) GETSTRUCT(tuple); + + attnum = attTup->attnum; + if (attnum <= 0) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot alter system column \"%s\"", + colName))); + + if (attTup->attgenerated) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("column \"%s\" of relation \"%s\" is already a generated column", + colName, RelationGetRelationName(rel)))); + + /* Mark as generated stored in pg_attribute */ + pg_attribute = table_open(AttributeRelationId, RowExclusiveLock); + attTup->attgenerated = ATTRIBUTE_GENERATED_STORED; + CatalogTupleUpdate(pg_attribute, &tuple->t_self, tuple); + table_close(pg_attribute, RowExclusiveLock); + + /* Make above changes visible */ + CommandCounterIncrement(); + + ReleaseSysCache(tuple); + + /* + * Find everything that depends on the column (constraints, indexes, etc), + * and record enough information to let us recreate the objects. + */ + RememberAllDependentForRebuilding(tab, AT_AddGeneratedAsExprStored, + rel, attnum, colName); + + /* + * Remove previous default value, if any, and store the new generator + * expression. + */ + RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, + false, false); + + rawEnt = palloc_object(RawColumnDefault); + rawEnt->attnum = attnum; + rawEnt->raw_default = def->raw_expr; + rawEnt->generated = def->generated_kind; + AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, + false, true, false, NULL); + + /* Make above changes visible */ + CommandCounterIncrement(); + + /* + * Clear all the missing values if we're rewriting the table, since this + * renders them pointless. + */ + RelationClearMissing(rel); + + /* Make above changes visible */ + CommandCounterIncrement(); + + /* Drop any pg_statistic entry for the column */ + RemoveStatistics(RelationGetRelid(rel), attnum); + + /* Build a concrete expression for the new default (generated) value */ + defval = (Expr *) build_column_default(rel, attnum); + defval = expression_planner(defval); + + /* Schedule a rewrite */ + newval = palloc0_object(NewColumnValue); + newval->attnum = attnum; + newval->expr = defval; + newval->is_generated = true; + tab->newvals = lappend(tab->newvals, newval); + tab->rewrite |= AT_REWRITE_DEFAULT_VAL; + + InvokeObjectPostAlterHook(RelationRelationId, + RelationGetRelid(rel), attnum); + + ObjectAddressSubSet(address, RelationRelationId, + RelationGetRelid(rel), attnum); + return address; +} + /* * ALTER TABLE ALTER COLUMN DROP EXPRESSION */ @@ -15320,7 +15502,9 @@ RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, SysScanDesc scan; HeapTuple depTup; - Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression); + Assert(subtype == AT_AlterColumnType + || subtype == AT_SetExpression + || subtype == AT_AddGeneratedAsExprStored); depRel = table_open(DependRelationId, RowExclusiveLock); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index ff4e1388c55..8cd75572257 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -2725,6 +2725,37 @@ alter_table_cmd: n->name = $3; n->def = (Node *) c; + $$ = (Node *) n; + } + /* ALTER TABLE <name> ALTER [COLUMN] <colname> ADD GENERATED ALWAYS AS ( <expression> ) STORED */ + | ALTER opt_column ColId ADD_P GENERATED generated_when AS '(' a_expr ')' STORED + { + AlterTableCmd *n = makeNode(AlterTableCmd); + Constraint *c = makeNode(Constraint); + + c->contype = CONSTR_GENERATED; + c->generated_when = $6; + c->raw_expr = $9; + c->cooked_expr = NULL; + c->generated_kind = ATTRIBUTE_GENERATED_STORED; + c->location = @5; + + /* + * Like in the case of ColConstraintElem, we cannot handle + * this in the grammar because IDENTITY allows both ALWAYS + * and BY DEFAULT, while generated columns only allow + * ALWAYS. This would lead to shift/reduce conflicts. + */ + if (c->generated_when != ATTRIBUTE_IDENTITY_ALWAYS) + ereport(ERROR, + (errcode(ERRCODE_SYNTAX_ERROR), + errmsg("for a generated column, GENERATED ALWAYS must be specified"), + parser_errposition(@6))); + + n->subtype = AT_AddGeneratedAsExprStored; + n->name = $3; + n->def = (Node *) c; + $$ = (Node *) n; } /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET <sequence options>/RESET */ diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 91377a6cde3..620e2dd73bf 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -2527,6 +2527,7 @@ typedef enum AlterTableType AT_CookedColumnDefault, /* add a pre-cooked column default */ AT_DropNotNull, /* alter column drop not null */ AT_SetNotNull, /* alter column set not null */ + AT_AddGeneratedAsExprStored, /* add generated always as (...) stored */ AT_SetExpression, /* alter column set expression */ AT_DropExpression, /* alter column drop expression */ AT_SetStatistics, /* alter column set statistics */ diff --git a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c index 64a1dfa9f79..3132ceac61f 100644 --- a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c +++ b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c @@ -129,6 +129,9 @@ get_altertable_subcmdinfo(PG_FUNCTION_ARGS) case AT_SetNotNull: strtype = "SET NOT NULL"; break; + case AT_AddGeneratedAsExprStored: + strtype = "ADD GENERATED ALWAYS AS (...) STORED"; + break; case AT_SetExpression: strtype = "SET EXPRESSION"; break; diff --git a/src/test/regress/expected/alter_table.out b/src/test/regress/expected/alter_table.out index 6dd22be0e8d..08981f4e380 100644 --- a/src/test/regress/expected/alter_table.out +++ b/src/test/regress/expected/alter_table.out @@ -4875,3 +4875,129 @@ drop publication pub1; drop schema alter1 cascade; drop schema alter2 cascade; NOTICE: drop cascades to table alter2.t1 +-- Tests for ALTER COLUMN ... ADD GENERATED ALWAYS as ( expr ) STORED +-- turning a regular column into a stored generated column +create schema testgen; +create table testgen.t1 (a int, b int not null); +insert into testgen.t1 (a, b) + select x, x from generate_series(1, 10) x; +alter table testgen.t1 alter column b + add generated always as (a * 2) stored; +\d+ testgen.t1 + Table "testgen.t1" + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+------------------------------------+---------+--------------+------------- + a | integer | | | | plain | | + b | integer | | not null | generated always as (a * 2) stored | plain | | +Not-null constraints: + "t1_b_not_null" NOT NULL "b" + +select a, b, a * 2 as expected, b = (a * 2) as correct + from testgen.t1 order by a; + a | b | expected | correct +----+----+----------+--------- + 1 | 2 | 2 | t + 2 | 4 | 4 | t + 3 | 6 | 6 | t + 4 | 8 | 8 | t + 5 | 10 | 10 | t + 6 | 12 | 12 | t + 7 | 14 | 14 | t + 8 | 16 | 16 | t + 9 | 18 | 18 | t + 10 | 20 | 20 | t +(10 rows) + +insert into testgen.t1 (a, b) values (10, 20); +ERROR: cannot insert a non-DEFAULT value into column "b" +DETAIL: Column "b" is a generated column. +insert into testgen.t1 (a, b) values (10, 21); +ERROR: cannot insert a non-DEFAULT value into column "b" +DETAIL: Column "b" is a generated column. +drop table testgen.t1; +-- turning a regular column into a stored generated column +-- fails when another constraint conflicts with the new expression +create table testgen.t2 (a int, b int not null); +insert into testgen.t2 (a, b) select x, x * 2 from generate_series(0, 5) x; +alter table testgen.t2 add constraint chk_gen_clause check (b = a * 2); +select pg_relation_filenode('testgen.t2') as t2_filenode_before \gset +alter table testgen.t2 alter column b add generated always as (a * 3) stored; +ERROR: check constraint "chk_gen_clause" of relation "t2" is violated by some row +select pg_relation_filenode('testgen.t2') as t2_filenode_after \gset +select :t2_filenode_before = :t2_filenode_after as did_not_rewrite; + did_not_rewrite +----------------- + t +(1 row) + +\d+ testgen.t2 + Table "testgen.t2" + Column | Type | Collation | Nullable | Default | Storage | Stats target | Description +--------+---------+-----------+----------+---------+---------+--------------+------------- + a | integer | | | | plain | | + b | integer | | not null | | plain | | +Check constraints: + "chk_gen_clause" CHECK (b = (a * 2)) +Not-null constraints: + "t2_b_not_null" NOT NULL "b" + +drop table testgen.t2; +-- rewrite an indexed column +create table testgen.t3 (a int, b int); +create index idx_b on testgen.t3 (b); +insert into testgen.t3 (a, b) select x, x from generate_series(1, 10) x; +select pg_relation_filenode('testgen.idx_b') as idx_filenode_before \gset +alter table testgen.t3 alter column b add generated always as (a * 2) stored; +select pg_relation_filenode('testgen.idx_b') as idx_filenode_after \gset +select :idx_filenode_before != :idx_filenode_after as did_rewrite_idx; + did_rewrite_idx +----------------- + t +(1 row) + +-- tests for invalid invocations +alter table doesnotexist alter column foo + add generated always as (bar * 2) stored; +ERROR: relation "doesnotexist" does not exist +create table testgen.t1 (a int); +alter table testgen.t1 alter column doesnotexist + add generated always as (bar * 2) stored; +ERROR: column "doesnotexist" of relation "t1" does not exist +alter table testgen.t1 add column b int; +alter table testgen.t1 alter column b + add generated always as (doesnotexist * 2) stored; +ERROR: column "doesnotexist" does not exist +-- invalid: only supports ALWAYS +alter table testgen.t1 alter column b + add generated by default as (a * 2) stored; +ERROR: for a generated column, GENERATED ALWAYS must be specified +LINE 2: add generated by default as (a * 2) stored; + ^ +-- invalid: only supports STORED +alter table testgen.t1 alter column b add generated always as (a * 2); +ERROR: syntax error at or near ";" +LINE 1: ...e testgen.t1 alter column b add generated always as (a * 2); + ^ +alter table testgen.t1 alter column b add generated always as (a * 2) virtual; +ERROR: syntax error at or near "virtual" +LINE 1: ...n.t1 alter column b add generated always as (a * 2) virtual; + ^ +-- invalid: b is already a generated column +create table testgen.t2 (a int, b int generated always as (a * 2) stored); +alter table testgen.t2 alter column b add generated always as (a * 2) stored; +ERROR: column "b" of relation "t2" is already a generated column +drop table testgen.t2; +create table testgen.t3 (a int, b int); +-- invalid: expr must be immutable +alter table testgen.t3 alter column b + add generated always as (a + random()) stored; +ERROR: generation expression is not immutable +-- invalid: expr cannot use subselects +alter table testgen.t3 alter column b + add generated always as (a + (select 1)) stored; +ERROR: cannot use subquery in column generation expression +drop table testgen.t3; +drop schema testgen cascade; +NOTICE: drop cascades to 4 other objects +DETAIL: drop cascades to table testgen.t3 +drop cascades to table testgen.t1 diff --git a/src/test/regress/sql/alter_table.sql b/src/test/regress/sql/alter_table.sql index f5f13bbd3e7..76187083289 100644 --- a/src/test/regress/sql/alter_table.sql +++ b/src/test/regress/sql/alter_table.sql @@ -3159,3 +3159,79 @@ alter table alter1.t1 set schema alter2; drop publication pub1; drop schema alter1 cascade; drop schema alter2 cascade; + +-- Tests for ALTER COLUMN ... ADD GENERATED ALWAYS as ( expr ) STORED +-- turning a regular column into a stored generated column +create schema testgen; + +create table testgen.t1 (a int, b int not null); +insert into testgen.t1 (a, b) + select x, x from generate_series(1, 10) x; +alter table testgen.t1 alter column b + add generated always as (a * 2) stored; +\d+ testgen.t1 +select a, b, a * 2 as expected, b = (a * 2) as correct + from testgen.t1 order by a; +insert into testgen.t1 (a, b) values (10, 20); +insert into testgen.t1 (a, b) values (10, 21); +drop table testgen.t1; + +-- turning a regular column into a stored generated column +-- fails when another constraint conflicts with the new expression +create table testgen.t2 (a int, b int not null); +insert into testgen.t2 (a, b) select x, x * 2 from generate_series(0, 5) x; +alter table testgen.t2 add constraint chk_gen_clause check (b = a * 2); +select pg_relation_filenode('testgen.t2') as t2_filenode_before \gset +alter table testgen.t2 alter column b add generated always as (a * 3) stored; +select pg_relation_filenode('testgen.t2') as t2_filenode_after \gset +select :t2_filenode_before = :t2_filenode_after as did_not_rewrite; +\d+ testgen.t2 +drop table testgen.t2; + +-- rewrite an indexed column +create table testgen.t3 (a int, b int); +create index idx_b on testgen.t3 (b); +insert into testgen.t3 (a, b) select x, x from generate_series(1, 10) x; +select pg_relation_filenode('testgen.idx_b') as idx_filenode_before \gset +alter table testgen.t3 alter column b add generated always as (a * 2) stored; +select pg_relation_filenode('testgen.idx_b') as idx_filenode_after \gset +select :idx_filenode_before != :idx_filenode_after as did_rewrite_idx; +drop table testgen.t3; + +-- tests for invalid invocations +alter table doesnotexist alter column foo + add generated always as (bar * 2) stored; + +create table testgen.t1 (a int); + +alter table testgen.t1 alter column doesnotexist + add generated always as (bar * 2) stored; + +alter table testgen.t1 add column b int; + +alter table testgen.t1 alter column b + add generated always as (doesnotexist * 2) stored; + +-- invalid: only supports ALWAYS +alter table testgen.t1 alter column b + add generated by default as (a * 2) stored; + +-- invalid: only supports STORED +alter table testgen.t1 alter column b add generated always as (a * 2); +alter table testgen.t1 alter column b add generated always as (a * 2) virtual; + +-- invalid: b is already a generated column +create table testgen.t2 (a int, b int generated always as (a * 2) stored); +alter table testgen.t2 alter column b add generated always as (a * 2) stored; +drop table testgen.t2; + +create table testgen.t3 (a int, b int); +-- invalid: expr must be immutable +alter table testgen.t3 alter column b + add generated always as (a + random()) stored; +-- invalid: expr cannot use subselects +alter table testgen.t3 alter column b + add generated always as (a + (select 1)) stored; +drop table testgen.t3; + +drop schema testgen cascade; base-commit: 3b28dad70e2fa57a973697d51242c284d475c7df -- 2.47.0 --4wx636ozsu2eakgd Content-Type: text/x-patch; charset=utf-8 Content-Disposition: attachment; filename="v3-0002-Try-to-avoid-a-rewrite-when-adding-a-stored-gener.patch" ^ permalink raw reply [nested|flat] 188+ messages in thread
end of thread, other threads:[~2026-04-24 08:44 UTC | newest] Thread overview: 188+ 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-24 08:44 [PATCH v3 1/2] Support changing a column into a stored generated column Alberto Piai <[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