tablecmds: Deadlock caused by Attach Partition

Поиск
Список
Период
Сортировка
Искать

tablecmds: Deadlock caused by Attach Partition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:
Вложения:
Hi Hacker,

This issue was initially discovered while working on patch [1], which makes REPLICA IDENTITY recurse from a partitioned table down to all partitions. The deadlock test itself was originally designed by Dmitry Dolgov (see [2]). After further investigation, I confirmed that this deadlock is actually a more general problem and can be reliably reproduced on the current master branch.

How to reproduce?
==============

1. Edit the attached script with changing the db name to your own, then run the attached sh script in a terminal. Basically the script creates a deep partition chain: test1<-test2<-test3<-… <-test1000.
2. In the other thermal, start a psql session, and repeatedly run “ALTER TABLE test1 ALTER COLUMN id SET DEFAULT 0;”, then you should quickly see a deadlock error reported in the server log.

My analysis
=========

Let’s first look at the server log:
```
2026-01-29 16:36:14.308 CST [50910] DETAIL: Process 50910 waits for AccessExclusiveLock on relation 38382 of database 16384; blocked by process 69148.
Process 69148 waits for AccessShareLock on relation 38376 of database 16384; blocked by process 50910.
Process 50910: ALTER TABLE test1 ALTER COLUMN id SET DEFAULT 0;
Process 69148: alter table test334 attach partition test335 for values from (335) to (1000000000);
```

Here relation 38376 was table test29, and relation 38382 was table test30. In other words:

 * ALTER TABLE (let’s call it session A) was waiting for a lock on table30, 
 * ATTACH PARTITION (let’s call it session B) was waiting for a lock on test29. 

At the time:

  * session A held lock on test29 and requesting lock on test30; 
  * session B held lock on test30 and requesting lock on test29;

This circular wait leads directly to the deadlock. I then analyzed the lock behavior of both sessions.

For Session A: ALTER COLUMN SET DEFAULT:

  * ALTER TABLE aways locks the target table, so test1 locked first
  * Since SET DEFAULT recurses to partitions, ATSimpleRecursion() is used to propagate the command. During this process, find_all_inheritors() is called to locate all partitions, sort them by OID, and then lock them one by one.
  * As a result, locks are acquired in the order test2, test3, … up to the last existing partition.

This explains why session A held a lock on test29 and was requesting a lock on test30.

From Session B: ATTACH PARTITION: 

Session B was requesting an AccessShareLock. Based on this, I traced the lock request to generate_partition_qual(), which is a recursive function. It walks up the partition tree to collect all partition quals, meaning that ATTACH PARTITION locks all ancestors in reverse OID order.

That explains why session B held a lock on test30 and was requesting a lock on test29.

Proposed solution
==============

The root cause is inconsistent lock ordering.

A simple solution is to pre-lock all ancestors for ATTACH PARTITION in OID order. That way, when generate_partition_qual() later recurses up the partition tree, all required locks have already been acquired.

One important detail is that these ancestor locks must be taken before the ALTER TABLE infrastructure locks the target table; otherwise, the lock order still cannot be guaranteed. With this in mind, I found that RangeVarCallbackForAlterRelation() is the appropriate place to perform this pre-locking.

Please see the attached v1 patch for the implementation.

Potential issue remaining 
===================

Currently, find_all_inheritors() sorts all inheritors purely by OID. In most cases this works, because users typically create a partitioned table first and then add partitions later, so the partitioned table’s OID is smaller than those of its partitions.

However, this is not always true. For example, if a user creates a regular table A first, then creates a partitioned table P, and later attaches A to P, P’s OID will be larger than A’s. If such a case is reported in the future, I think we should enhance find_all_inheritors() to always lock the parent first, and only sort siblings at the same level by OID.

This patch has not addressed that potential issue.


[1] https://postgr.es/m/CAEoWx2nJ71hy8R614HQr7vQhkBReO9AANPODPg0aSQs74eOdLQ@mail.gmail.com
[2] https://www.postgresql.org/message-id/flat/201902041630.gpadougzab7v%40alvherre.pgsql

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/



Re: tablecmds: Deadlock caused by Attach Partition

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Вложения:
Hi Chao,

I looked at v1 and tried the problem on master. I have some comments below.
I'm also attaching an isolation test, to be applied on top of your v1
(in reply to Rafia's request). It needs no injection point, so it could replace the one Kirill posted.

1. The INSERT-into-a-partition variant of this deadlock (ExecPartitionCheck() -> generate_partition_qual() locking the parents
while the partition is already locked) was discussed in 2021 [1], and the conclusion there was that child-first, then parent, locking is inherent
for DML on a partition and accepted as rare. I reproduced that variant on master too, and v1 doesn't (and can't) cover it, since the partition is
locked during parse analysis. ATTACH is different in that it can lock the ancestors before the target, so I think the narrow fix is reasonable, but
it might be worth saying in the commit message that the DML case is known and intentionally out of scope.

2. RangeVarCallbackForDropRelation() already does the same thing for DROP of a partition, it locks the parent before the partition
"because queries lock the parent before its partitions, so we risk deadlock if we do it the other way around." That supports doing this in
the RangeVar callback. Two things it does that v1 doesn't:

i) It only takes the lock when relOid != oldRelOid, and releases the lock taken for a previous lookup if the name now resolves to a
different relation. v1 redoes get_partition_ancestors() on every callback invocation and keeps locks on the ancestors of a relation
the name no longer refers to.

ii) It uses get_partition_parent(relOid, true), i.e. it follows a parent link that is pending detach. v1 uses get_partition_ancestors(), which
stops at a detach-pending link, while generate_partition_qual() calls get_partition_parent(..., true) and keeps going. So if the
target (or an ancestor) is in the middle of DETACH CONCURRENTLY, the pre-lock covers fewer ancestors than the later walk. I haven't
 looked at whether a recursing ALTER TABLE can still deadlock with it in that state, since find_all_inheritors() may skip the detached
partition, but either way it would be good to say whether the difference is intended.

3. The commit message says find_all_inheritors() locks partitions "in ascending OID order" and that the patch pre-locks
ancestors "in OID order". The code locks ancestors root-first using pg_inherits, which is the right thing. find_all_inheritors() goes one
level at a time and sorts only siblings by OID (find_inheritance_children_extended(), pg_inherits.c), so parents are
always locked before children whatever their OIDs. So the "potential issue remaining" in your first mail doesn't apply to this patch, and I think the
commit message should say "root to parent" rather than OID order. (Kirill, small correction on your note, the sorting happens per level, in
find_inheritance_children_extended(), not across the whole tree.)

4. Small things in the code:
    - lock_partition_ancestors() returns the ancestor list, but the only caller ignores it, so the list is just allocated and dropped. Could it
      return void, or be a short loop in tablecmds.c instead of a new function in partition.c?
    - "The target table must be a partitioned table, but if, we don't need to fail here;" is not very clear. Maybe "If the target is not a
      partitioned table, don't fail here; ALTER TABLE will report that later."
    - +1 to Rafia on pgindent; git show --check also flags trailing whitespace on both "/* " lines.

5. The attached test is (0002-Add-isolation-test-for-ATTACH-PARTITION-lock-orderin.patch)
src/test/isolation/specs/partition-attach-lock-order.spec. It doesn't need an injection point: session 1 runs LOCK TABLE ONLY root IN ACCESS
EXCLUSIVE MODE (only the root, the way the recursing ALTER TABLE has it before it recurses), session 2 runs ATTACH PARTITION on a mid-level
table, then session 1 runs the recursing ALTER TABLE. It uses three levels (root > mid1 > mid2, attaching to mid2), so pre-locking only the direct parent would still deadlock on mid1.

With v1 applied the test passes. Without v1 (unpatched master), s2attach has locked mid2 and then mid1 while walking up for the partition
constraint, and waits for the root, which s1 holds. s1alter, recursing from the root, waits for mid1, which s2attach holds. The deadlock detector
aborts the ATTACH:

    step s1alter: ALTER TABLE attach_lock_root ALTER COLUMN id SET DEFAULT 0; <waiting ...>
    step s1alter: <... completed>
    step s2attach: <... completed>
    ERROR:  deadlock detected

Note that the deadlock only happens when session 2 hasn't cached the target's partition constraint yet (generate_partition_qual() returns the
cached copy without locking anything). The isolation sessions connect before setup creates the tables, so the cache is always cold there. This
is also why a fresh session for every ATTACH reproduces it so easily.

Feel free to fold the test into your next version.
(Note: v1 is unchanged and is same as Chao's v1) 

[1] https://postgr.es/m/CAA4eK1LsFpjK5gL+0HEvoqB2DJVOi19vGAWbZBEx8fACOi5+_A@mail.gmail.com

Regards,
Surya Poondla


Re: tablecmds: Deadlock caused by Attach Partition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:
Вложения:


> On Oct 20, 2026, at 03:06, surya poondla  wrote:
> 
> Hi Chao,
> 
> I looked at v1 and tried the problem on master. I have some comments below.

Thanks a lot for your review.

> I'm also attaching an isolation test, to be applied on top of your v1
> (in reply to Rafia's request). It needs no injection point, so it could replace the one Kirill posted.
> 
> 1. The INSERT-into-a-partition variant of this deadlock (ExecPartitionCheck() -> generate_partition_qual() locking the parents
> while the partition is already locked) was discussed in 2021 [1], and the conclusion there was that child-first, then parent, locking is inherent
> for DML on a partition and accepted as rare. I reproduced that variant on master too, and v1 doesn't (and can't) cover it, since the partition is
> locked during parse analysis. ATTACH is different in that it can lock the ancestors before the target, so I think the narrow fix is reasonable, but
> it might be worth saying in the commit message that the DML case is known and intentionally out of scope.

Let’s keep the scope of this patch narrowed. I have updated the commit message.

> 
> 2. RangeVarCallbackForDropRelation() already does the same thing for DROP of a partition, it locks the parent before the partition
> "because queries lock the parent before its partitions, so we risk deadlock if we do it the other way around." That supports doing this in
> the RangeVar callback. Two things it does that v1 doesn't:
> 
> i) It only takes the lock when relOid != oldRelOid, and releases the lock taken for a previous lookup if the name now resolves to a
> different relation. v1 redoes get_partition_ancestors() on every callback invocation and keeps locks on the ancestors of a relation
> the name no longer refers to.
> 

This is an old patch. When I created it, TBH, I wasn’t aware the callback retry mechanism. In v2, I switched to a similar way of RangeVarCallbackForDropRelation to remember locked ancestors and release them upon retry.

> ii) It uses get_partition_parent(relOid, true), i.e. it follows a parent link that is pending detach. v1 uses get_partition_ancestors(), which
> stops at a detach-pending link, while generate_partition_qual() calls get_partition_parent(..., true) and keeps going. So if the
> target (or an ancestor) is in the middle of DETACH CONCURRENTLY, the pre-lock covers fewer ancestors than the later walk. I haven't
>  looked at whether a recursing ALTER TABLE can still deadlock with it in that state, since find_all_inheritors() may skip the detached
> partition, but either way it would be good to say whether the difference is intended.

Good catch. Fixed in v2.

> 
> 3. The commit message says find_all_inheritors() locks partitions "in ascending OID order" and that the patch pre-locks
> ancestors "in OID order". The code locks ancestors root-first using pg_inherits, which is the right thing. find_all_inheritors() goes one
> level at a time and sorts only siblings by OID (find_inheritance_children_extended(), pg_inherits.c), so parents are
> always locked before children whatever their OIDs. So the "potential issue remaining" in your first mail doesn't apply to this patch, and I think the
> commit message should say "root to parent" rather than OID order. (Kirill, small correction on your note, the sorting happens per level, in
> find_inheritance_children_extended(), not across the whole tree.)

Updated the commit message.

> 
> 4. Small things in the code:
>     - lock_partition_ancestors() returns the ancestor list, but the only caller ignores it, so the list is just allocated and dropped. Could it
>       return void, or be a short loop in tablecmds.c instead of a new function in partition.c?

V2 now uses the returned list.

>     - "The target table must be a partitioned table, but if, we don't need to fail here;" is not very clear. Maybe "If the target is not a
>       partitioned table, don't fail here; ALTER TABLE will report that later."

Updated the comment.

>     - +1 to Rafia on pgindent; git show --check also flags trailing whitespace on both "/* " lines.

Ran pgindent on v2.

> 
> 5. The attached test is (0002-Add-isolation-test-for-ATTACH-PARTITION-lock-orderin.patch)
> src/test/isolation/specs/partition-attach-lock-order.spec. It doesn't need an injection point: session 1 runs LOCK TABLE ONLY root IN ACCESS
> EXCLUSIVE MODE (only the root, the way the recursing ALTER TABLE has it before it recurses), session 2 runs ATTACH PARTITION on a mid-level
> table, then session 1 runs the recursing ALTER TABLE. It uses three levels (root > mid1 > mid2, attaching to mid2), so pre-locking only the direct parent would still deadlock on mid1.
> 
> With v1 applied the test passes. Without v1 (unpatched master), s2attach has locked mid2 and then mid1 while walking up for the partition
> constraint, and waits for the root, which s1 holds. s1alter, recursing from the root, waits for mid1, which s2attach holds. The deadlock detector
> aborts the ATTACH:
> 
>     step s1alter: ALTER TABLE attach_lock_root ALTER COLUMN id SET DEFAULT 0; 
>     step s1alter: <... completed>
>     step s2attach: <... completed>
>     ERROR:  deadlock detected
> 
> Note that the deadlock only happens when session 2 hasn't cached the target's partition constraint yet (generate_partition_qual() returns the
> cached copy without locking anything). The isolation sessions connect before setup creates the tables, so the cache is always cold there. This
> is also why a fresh session for every ATTACH reproduces it so easily.
> 
> Feel free to fold the test into your next version.
> (Note: v1 is unchanged and is same as Chao's v1) 

Your test looks good to me. I’d keep it in 0002 and let the committer decide whether or not to accept it.

> 
> [1] https://postgr.es/m/CAA4eK1LsFpjK5gL+0HEvoqB2DJVOi19vGAWbZBEx8fACOi5+_A@mail.gmail.com
> 
> Regards,
> Surya Poondla
> 
> 
> <0002-Add-isolation-test-for-ATTACH-PARTITION-lock-orderin.patch><0001-Prevent-deadlock-between-ALTER-TABLE-recursion-and-A.patch>

PFA v2:

* 0001 - Addressed all review comments
* 0002 - The same Surya as posted, only added Author and Reviewed-by annotations

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/




Re: tablecmds: Deadlock caused by Attach Partition

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,

Thanks for v2. I applied both patches to the current master, they apply cleanly and build without warnings. I ran the new
partition-attach-lock-order isolation test together with partition-concurrent-attach and partition-drop-index-locking against the
v2 build, and all three pass.

The retry handling looks right to me. RangeVarGetRelidExtended() calls the callback before each lock attempt, including retries, so a same-OID
retry keeps the ancestor locks, a different-OID retry releases them before locking the new ones, and a name that no longer resolves releases
the old ancestors and locks nothing. Following detach-pending links also now matches what generate_partition_qual() code.

Two small comments, neither blocking:
1. lock_partition_ancestors() is also called for a top-level partitioned table, which has no parent, so it scans pg_inherits and finds nothing.
Checking get_rel_relispartition(relid) in the callback before calling it would skip that. It would also fit the comment on
get_partition_ancestors(), which says ancestors should only be looked up for a partition.

2. The ancestors are computed before the target is locked and aren't rechecked afterwards, so if the target is reparented in between,
generate_partition_qual() could still walk an ancestor that wasn't pre-locked. RangeVarCallbackForDropRelation() has the same gap, so I
think it's acceptable, but a short comment saying so might help.

One wording nit in the commit message: "the partition is already locked during parse analysis" is only true for a freshly parsed statement. For a
cached plan (prepared statement, PL/pgSQL) the lock is taken in the plancache before execution. Something like "the partition is already
locked before its ancestors are locked to check partition constraints" is true on both paths. The phrase came from my first mail, so that one is
on me.


Regards,
Surya Poondla

Re: tablecmds: Deadlock caused by Attach Partition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:
Вложения:


> On Oct 21, 2026, at 05:24, surya poondla  wrote:
> 
> Hi Chao,
> 
> Thanks for v2. I applied both patches to the current master, they apply cleanly and build without warnings. I ran the new
> partition-attach-lock-order isolation test together with partition-concurrent-attach and partition-drop-index-locking against the
> v2 build, and all three pass.
> 
> The retry handling looks right to me. RangeVarGetRelidExtended() calls the callback before each lock attempt, including retries, so a same-OID
> retry keeps the ancestor locks, a different-OID retry releases them before locking the new ones, and a name that no longer resolves releases
> the old ancestors and locks nothing. Following detach-pending links also now matches what generate_partition_qual() code.
> 
> Two small comments, neither blocking:
> 1. lock_partition_ancestors() is also called for a top-level partitioned table, which has no parent, so it scans pg_inherits and finds nothing.
> Checking get_rel_relispartition(relid) in the callback before calling it would skip that. It would also fit the comment on
> get_partition_ancestors(), which says ancestors should only be looked up for a partition.
> 

Good point. Addressed in v3.

> 2. The ancestors are computed before the target is locked and aren't rechecked afterwards, so if the target is reparented in between,
> generate_partition_qual() could still walk an ancestor that wasn't pre-locked. RangeVarCallbackForDropRelation() has the same gap, so I
> think it's acceptable, but a short comment saying so might help.
> 

Add a comment for that in v3.

> One wording nit in the commit message: "the partition is already locked during parse analysis" is only true for a freshly parsed statement. For a
> cached plan (prepared statement, PL/pgSQL) the lock is taken in the plancache before execution. Something like "the partition is already
> locked before its ancestors are locked to check partition constraints" is true on both paths. The phrase came from my first mail, so that one is
> on me.

Updated 0001’s commit message.

PFA v3:

* 0001 - addressed Surya’s comments
* 0002 - unchanged

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/




Re: tablecmds: Deadlock caused by Attach Partition

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,

Thanks for v3. I applied both patches to master as of fded90eec3e, they apply cleanly and build without warnings. With v3,
partition-attach-lock-order, partition-concurrent-attach and partition-drop-index-locking all pass. On an unpatched build of the same
commit, partition-attach-lock-order fails with "deadlock detected" in the ATTACH step (s2attach) and the other two pass, so the test still catches
the bug. The v3 changes address my comments.

Regarding the approach, I think pre-locking in the RangeVar callback is the right place, and probably the only one that works. By the time
generate_partition_qual() runs, the target is already locked, so taking the ancestor locks top-down there would still leave the target locked
before its ancestors. RangeVarCallbackForDropRelation() does a similar thing for DROP (it locks the parent before the partition), so it is fine this way too.

One behavior change worth mentioning in the commit message. With a warm partition-constraint cache, generate_partition_qual() returns the cached
copy without locking, so on master an ATTACH doesn't always lock every ancestor. I checked pg_locks after ALTER TABLE mid2 ATTACH PARTITION in a
3-level tree (in a single-user backend), on master with mid2's cache warmed first, the root isn't locked (mid1 still is), with v3 the root and
mid1 are always locked in AccessShareLock, the same as master does with a cold cache. So with v3, ATTACH on a mid-level table always takes a lock
on the root, which on master it doesn't hold when the cache is warm. I think that's fine, since it only makes the lock set independent of cache
state, but a sentence saying so would help a committer.

Otherwise v3 looks good to me.

Regards,
Surya Poondla

Re: tablecmds: Deadlock caused by Attach Partition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:
Вложения:


> On Oct 22, 2026, at 05:46, surya poondla  wrote:
> 
> Hi Chao,
> 
> Thanks for v3. I applied both patches to master as of fded90eec3e, they apply cleanly and build without warnings. With v3,
> partition-attach-lock-order, partition-concurrent-attach and partition-drop-index-locking all pass. On an unpatched build of the same
> commit, partition-attach-lock-order fails with "deadlock detected" in the ATTACH step (s2attach) and the other two pass, so the test still catches
> the bug. The v3 changes address my comments.

Thank you very much for continuous reviewing.

> 
> Regarding the approach, I think pre-locking in the RangeVar callback is the right place, and probably the only one that works. By the time
> generate_partition_qual() runs, the target is already locked, so taking the ancestor locks top-down there would still leave the target locked
> before its ancestors. RangeVarCallbackForDropRelation() does a similar thing for DROP (it locks the parent before the partition), so it is fine this way too.
> 
> One behavior change worth mentioning in the commit message. With a warm partition-constraint cache, generate_partition_qual() returns the cached
> copy without locking, so on master an ATTACH doesn't always lock every ancestor. I checked pg_locks after ALTER TABLE mid2 ATTACH PARTITION in a
> 3-level tree (in a single-user backend), on master with mid2's cache warmed first, the root isn't locked (mid1 still is), with v3 the root and
> mid1 are always locked in AccessShareLock, the same as master does with a cold cache. So with v3, ATTACH on a mid-level table always takes a lock
> on the root, which on master it doesn't hold when the cache is warm. I think that's fine, since it only makes the lock set independent of cache
> state, but a sentence saying so would help a committer.
> 

Updated 0001’s commit message.

> Otherwise v3 looks good to me.
> 
> Regards,
> Surya Poondla

PFA v4 - only updated 0001’s commit per Surya’s suggestion.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/




Re: tablecmds: Deadlock caused by Attach Partition

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,

Thanks for v4. The new commit message paragraph describes the lock change accurately. I compared v4 with v3: the code in 0001 and the test
in 0002 are unchanged. I cross checked the v4 and its results look same as v3.

I think the patch is ready for a committer, and I've marked the CF entry Ready for Committer.

Regards,
Surya Poondla

Re: tablecmds: Deadlock caused by Attach Partition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Oct 23, 2026, at 02:05, surya poondla  wrote:
> 
> Hi Chao,
> 
> Thanks for v4. The new commit message paragraph describes the lock change accurately. I compared v4 with v3: the code in 0001 and the test
> in 0002 are unchanged. I cross checked the v4 and its results look same as v3.
> 
> I think the patch is ready for a committer, and I've marked the CF entry Ready for Committer.
> 
> Regards,
> Surya Poondla

Thank you so much for getting this patch ready for committer.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: tablecmds: Deadlock caused by Attach Partition

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-03, Kirill Reshke wrote:

> > Potential issue remaining
> > ===================
> >
> > Currently, find_all_inheritors() sorts all inheritors purely by OID.
> > In most cases this works, because users typically create a
> > partitioned table first and then add partitions later, so the
> > partitioned table’s OID is smaller than those of its partitions.

Hmm, I suppose I just added one more possibility for this kind of
deadlock failure with the 2ebd6849743 fix; maybe we should apply this
methodology to that code also.

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
 Are you not unsure you want to delete Firefox?
       [Not unsure]     [Not not unsure]    [Cancel]
                   http://smylers.hates-software.com/2008/01/03/566e45b2.html


Re: tablecmds: Deadlock caused by Attach Partition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:
Вложения:


> On Oct 25, 2026, at 17:32, Álvaro Herrera  wrote:
> 
> On 2026-Sep-03, Kirill Reshke wrote:
> 
>>> Potential issue remaining
>>> ===================
>>> 
>>> Currently, find_all_inheritors() sorts all inheritors purely by OID.
>>> In most cases this works, because users typically create a
>>> partitioned table first and then add partitions later, so the
>>> partitioned table’s OID is smaller than those of its partitions.
> 
> Hmm, I suppose I just added one more possibility for this kind of
> deadlock failure with the 2ebd6849743 fix; maybe we should apply this
> methodology to that code also.
> 
> -- 
> Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
> Are you not unsure you want to delete Firefox?
>       [Not unsure]     [Not not unsure]    [Cancel]
>                   http://smylers.hates-software.com/2008/01/03/566e45b2.html

Thanks for pointing out that, looks like ALTER INDEX ATTACH PARTITION has the same deadlock issue.

PFA v5:
* 0001 - just added one line comment based on v4-0001
* 0002 - fixed the ALTER INDEX ATTACH PARTITION by leveraging 0001’s mechanism
* 0003 - based on v4-0002, added a new test for 0002. Without 0002, the test will fail

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/




Re: tablecmds: Deadlock caused by Attach Partition

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,

Thanks for v5. I applied the three patches on top of b936425002c, which
has Álvaro's 2ebd6849743. Everything applies without conflicts
and builds without warnings. With v5, partition-attach-lock-order and the
new partition-index-attach-lock-order both pass, along with partition-concurrent-attach and partition-drop-index-locking. On an
unpatched build of the same commit, both lock-order specs fail with
"deadlock detected" in the ATTACH step, including the permutation with
two concurrent index ATTACHes, and the other two pass.

Nothing new from me on 0001. Apart from the moved comment and the change
to how the callback state is initialized, it's the same as v4.

0002 is where I spent most of my time. I wanted to see what locks ALTER
INDEX ... ATTACH PARTITION actually takes with and without the patch, so
I checked pg_locks in a single-user backend. I used a three-level tree,
root > mid1 > mid2 > {leaf1, leaf2}, created the partitioned indexes with ON ONLY so they start out invalid, and then ran ALTER INDEX mid2_idx
ATTACH PARTITION leaf1_idx.

When leaf2_idx isn't attached yet, mid2_idx stays invalid and nothing
above it gets validated. In that case master doesn't lock any of the
ancestors, but v5 takes AccessExclusiveLock on root, mid1, root_idx and
mid1_idx.

When leaf2_idx is already attached, this ATTACH completes mid2_idx and
validation cascades all the way up to root_idx. Here master and v5 take
the same locks (AccessExclusiveLock on those same four), and the indexes end up valid either way.

So the ordering is right for the cascading case, which is the one that matters for the deadlock. The catch is that every ATTACH on a partition
index now takes AccessExclusiveLock on all of its ancestor indexes and their tables, even when it isn't going to validate anything. In a full
index hierarchy that means the root table, so nobody can read or write the root until the ATTACH commits, and concurrent index ATTACHes in the
same tree would end up running one at a time. 

I can see why a weaker pre-lock doesn't work i.e validation would then have
to upgrade it to AccessExclusiveLock, and two ATTACHes doing that at the
same time could deadlock on the upgrade. Working out in the callback
whether this particular ATTACH will complete the parent doesn't look reliable either, because it depends on other ATTACHes that haven't
committed yet, which is exactly the race 2ebd6849743 fixed. I don't have a better idea, but I think the extra locking is worth a conscious
decision. Álvaro, what do you think, is that trade-off ok?

Regards,
Surya Poondla

Re: tablecmds: Deadlock caused by Attach Partition

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Hi Chao,

I looked at the other callers of generate_partition_qual() and race
each one against a recursive ALTER TABLE on the root, like Surya’s test.

pg_get_partition_constraintdef() has the same deadlock. It locks a
partition and then its ancestors through generate_partition_qual().
It deadlocks with a recursive ALTER TABLE on the root, psql \d+ uses it.

I think it can be fixed the same way. Call lock_partition_ancestors()
in get_partition_qual_relid() before it opens the relation.

It may also help to add a comment above generate_partition_qual() so
the next caller locks the ancestors first.

That could be a different patch or fix here, I am ok for both.

Thanks,
Shihao

Re: tablecmds: Deadlock caused by Attach Partition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Oct 28, 2026, at 09:29, shihao zhong  wrote:
> 
> Hi Chao,
> 
> I looked at the other callers of generate_partition_qual() and race
> each one against a recursive ALTER TABLE on the root, like Surya’s test.
> 
> pg_get_partition_constraintdef() has the same deadlock. It locks a
> partition and then its ancestors through generate_partition_qual().
> It deadlocks with a recursive ALTER TABLE on the root, psql \d+ uses it.
> 
> I think it can be fixed the same way. Call lock_partition_ancestors()
> in get_partition_qual_relid() before it opens the relation.
> 
> It may also help to add a comment above generate_partition_qual() so
> the next caller locks the ancestors first.
> 
> That could be a different patch or fix here, I am ok for both.
> 
> Thanks,
> Shihao
> 
> 

Hi Shihao,

Thanks for reporting a new deadlock scenario. After some investigation, I realized that there are more deadlock scenarios because of the current ALTER TABLE architecture. When altering a partitioned table and its partitions, ALTER TABLE needs to lock them top-down. If a concurrent session performs an operation that locks them bottom-up, a deadlock may occur. Besides generate_partition_qual(), which you pointed out, it seems ALTER TABLE ... ALTER COLUMN ... DROP NOT NULL also locks a partition before its parent, and I believe there are more cases.

This makes me reconsider the fix. I don’t feel we should fix these deadlock scenarios one by one. Instead, I’d pursue a common solution to address this type of deadlock, though I haven’t come up with a clear idea yet.

I don’t think this patch is urgent, because these deadlock problems have been there for many years, and few people have complained about them. In practice, I think these deadlocks should be hard to hit, and even if one occurs, retry should usually work. So, I’d hold off on this patch for a while.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






FAQ