From 69723f92d134fdfb454c6975f6be5621e0c4f3ad Mon Sep 17 00:00:00 2001
From: Pavel Borisov <pashkin.elfe@gmail.com>
Date: Mon, 23 Nov 2026 14:32:42 +0300
Subject: [PATCH v1] Avoid deadlock between CASCADE drop and concurrent index
 scan

CASCADE drops (e.g. DROP FUNCTION ... CASCADE) walk pg_depend and call
AcquireDeletionLock on each dependent object. For an index, this takes
AccessExclusiveLock on the index before index_drop() locks the parent
table. Regular queries and autovacuum lock table then index, so the
opposite order deadlocks.

Explicit DROP INDEX already avoids this since 2ad36c4e44c, where
RangeVarCallbackForDropRelation() locks the parent table first. Apply
the same ordering in AcquireDeletionLock: when the target is an index
or partitioned index, lock the parent table with AccessExclusiveLock
before locking the index.

Author: Pavel Borisov <pashkin.elfe@gmail.com>
Tests-by: Ilya Kobets <i.kobets@orioledb.com>
---
 src/backend/catalog/dependency.c              | 21 +++++++++++++++++++
 .../expected/partition-drop-index-locking.out | 15 ++++++++++++-
 .../specs/partition-drop-index-locking.spec   | 21 +++++++++++++++++++
 3 files changed, 56 insertions(+), 1 deletion(-)

diff --git a/src/backend/catalog/dependency.c b/src/backend/catalog/dependency.c
index 71e4dae193e..46745f2000c 100644
--- a/src/backend/catalog/dependency.c
+++ b/src/backend/catalog/dependency.c
@@ -1522,7 +1522,28 @@ AcquireDeletionLock(const ObjectAddress *object, int flags)
 		if (flags & PERFORM_DELETION_CONCURRENTLY)
 			LockRelationOid(object->objectId, ShareUpdateExclusiveLock);
 		else
+		{
+			/*
+			 * If this relation is an index, lock the parent table first.
+			 * index_drop() will need this anyway, and since regular queries
+			 * and autovacuum lock tables before their indexes, we risk
+			 * deadlock if we do it the other way around.  This mirrors the
+			 * logic in RangeVarCallbackForDropRelation(), which does the same
+			 * for explicit DROP INDEX but does not cover CASCADE drops.
+			 */
+			char		relkind = get_rel_relkind(object->objectId);
+
+			if (relkind == RELKIND_INDEX ||
+				relkind == RELKIND_PARTITIONED_INDEX)
+			{
+				Oid			heapOid = IndexGetRelation(object->objectId, true);
+
+				if (OidIsValid(heapOid))
+					LockRelationOid(heapOid, AccessExclusiveLock);
+			}
+
 			LockRelationOid(object->objectId, AccessExclusiveLock);
+		}
 	}
 	else if (IsSharedRelation(object->classId))
 		LockSharedObject(object->classId, object->objectId, 0,
diff --git a/src/test/isolation/expected/partition-drop-index-locking.out b/src/test/isolation/expected/partition-drop-index-locking.out
index 9acd51dfdef..c7ff8db779e 100644
--- a/src/test/isolation/expected/partition-drop-index-locking.out
+++ b/src/test/isolation/expected/partition-drop-index-locking.out
@@ -1,4 +1,4 @@
-Parsed test spec with 3 sessions
+Parsed test spec with 5 sessions
 
 starting permutation: s1begin s1lock s2begin s2drop s1select s3getlocks s1commit s3getlocks s2commit
 step s1begin: BEGIN;
@@ -98,3 +98,16 @@ DROP INDEX part_drop_index_locking_subpart_idx;|part_drop_index_locking_subpart_
 (4 rows)
 
 step s2commit: COMMIT;
+
+starting permutation: s1_cas_lock s2_cas_drop s1_cas_scan s1_cas_commit
+step s1_cas_lock: BEGIN; LOCK TABLE index_lock_t IN SHARE UPDATE EXCLUSIVE MODE;
+step s2_cas_drop: DROP FUNCTION index_lock_f(int) CASCADE; <waiting ...>
+step s1_cas_scan: SET enable_seqscan = off; SELECT count(*) FROM index_lock_t WHERE index_lock_f(a) = 5;
+count
+-----
+    1
+(1 row)
+
+step s1_cas_commit: COMMIT;
+s5: NOTICE:  drop cascades to index index_lock_t_f_idx
+step s2_cas_drop: <... completed>
diff --git a/src/test/isolation/specs/partition-drop-index-locking.spec b/src/test/isolation/specs/partition-drop-index-locking.spec
index 34e8b528b8d..86dceab6c7b 100644
--- a/src/test/isolation/specs/partition-drop-index-locking.spec
+++ b/src/test/isolation/specs/partition-drop-index-locking.spec
@@ -1,5 +1,9 @@
 # Verify that DROP INDEX properly locks all downward sub-partitions
 # and partitions before locking the indexes.
+#
+# Also verify that CASCADE drops lock the parent table before the
+# index, matching the table-then-index order used by queries and
+# autovacuum so that no deadlock occurs.
 
 setup
 {
@@ -8,11 +12,17 @@ setup
   CREATE TABLE part_drop_index_locking_subpart_child PARTITION OF part_drop_index_locking_subpart FOR VALUES FROM (1) TO (100);
   CREATE INDEX part_drop_index_locking_idx ON part_drop_index_locking(id);
   CREATE INDEX part_drop_index_locking_subpart_idx ON part_drop_index_locking_subpart(id);
+  CREATE FUNCTION index_lock_f(int) RETURNS int LANGUAGE sql IMMUTABLE AS 'SELECT $1';
+  CREATE TABLE index_lock_t (a int);
+  CREATE INDEX index_lock_t_f_idx ON index_lock_t (index_lock_f(a));
+  INSERT INTO index_lock_t SELECT generate_series(1, 1000);
 }
 
 teardown
 {
   DROP TABLE part_drop_index_locking;
+  DROP TABLE IF EXISTS index_lock_t;
+  DROP FUNCTION IF EXISTS index_lock_f(int);
 }
 
 # SELECT will take AccessShare lock first on the table and then on its index.
@@ -40,8 +50,19 @@ step s3getlocks {
         ORDER BY s.query, c.relname, l.mode, l.granted;
 }
 
+session s4
+step s1_cas_lock    { BEGIN; LOCK TABLE index_lock_t IN SHARE UPDATE EXCLUSIVE MODE; }
+step s1_cas_scan    { SET enable_seqscan = off; SELECT count(*) FROM index_lock_t WHERE index_lock_f(a) = 5; }
+step s1_cas_commit  { COMMIT; }
+
+session s5
+step s2_cas_drop    { DROP FUNCTION index_lock_f(int) CASCADE; }
+
 # Run DROP INDEX on top partitioned table
 permutation s1begin s1lock s2begin s2drop(s1commit) s1select s3getlocks s1commit s3getlocks s2commit
 
 # Run DROP INDEX on top sub-partition table
 permutation s1begin s1lock s2begin s2dropsub(s1commit) s1select s3getlocks s1commit s3getlocks s2commit
+
+# DROP FUNCTION whose CASCADE reaches the index
+permutation s1_cas_lock s2_cas_drop s1_cas_scan s1_cas_commit
-- 
2.50.1 (Apple Git-155)

