Avoid deadlock during orphan temp table removal.
authorTom Lane <[email protected]>
Tue, 2 Apr 2024 18:59:04 +0000 (14:59 -0400)
committerTom Lane <[email protected]>
Tue, 2 Apr 2024 18:59:04 +0000 (14:59 -0400)
commitca392df8dd183f93575dd21f1b76390656ca9550
treec0d2b1d42a4613f21b789b5be3666fdf390e6a80
parent0de5274f59c9d84d803d7f3dc75577d8aa6e56b8
Avoid deadlock during orphan temp table removal.

If temp tables have dependencies (such as sequences) then it's
possible for autovacuum's cleanup of orphan temp tables to deadlock
against an incoming backend that's trying to clean out the temp
namespace for its own use.  That can happen because RemoveTempRelations'
performDeletion call can visit objects within the namespace in
an order different from the order in which a per-table deletion
will visit them.

To fix, observe that performDeletion will begin by taking an exclusive
lock on the temp namespace (even though it won't actually delete it).
So, if we can get a shared lock on the namespace, we can be sure we're
not running concurrently with RemoveTempRelations, while also not
conflicting with ordinary use of the namespace.  This requires
introducing a conditional version of LockDatabaseObject, but that's no
big deal.  (It's surprising we've got along without that this long.)

Report and patch by Mikhail Zhilin.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/c43ce028-2bc2-4865-9b89-3f706246eed5@postgrespro.ru
src/backend/postmaster/autovacuum.c
src/backend/storage/lmgr/lmgr.c
src/include/storage/lmgr.h