Hi, hackers!

I found that CASCADE drops (DROP FUNCTION, DROP TYPE, DROP EXTENSION,
etc.) can deadlock with concurrent queries or autovacuum when a
dependent index is involved. Reproduction is in the patch attached.

The deadlock arises because AcquireDeletionLock() takes
AccessExclusiveLock on the index before index_drop() locks the parent
table, i.e. index-then-table order. Regular queries, ANALYZE and
VACUUM all lock in the opposite order: table then index. When both run
concurrently each holds one lock and waits for the other.

Explicit DROP INDEX avoids this since 2ad36c4e44c by pre-locking the
parent table in RangeVarCallbackForDropRelation(), but CASCADE drops
that reach the index through pg_depend bypass that callback and go
straight through AcquireDeletionLock(), hitting the reversed order.

Please see a patch with a simple fix: when AcquireDeletionLock() sees
an index or partitioned index, look up and lock the parent table
first, then lock the index, matching the order used everywhere else.

A deterministic test for the condition is also in the attached patch.

I think this is to be backpatched to all supported versions.

Regards,
Pavel Borisov
Supabase

Attachment: v1-0001-Avoid-deadlock-between-CASCADE-drop-and-concurren.patch
Description: Binary data

Reply via email to