Thread: BUG #17848: Deadlock when running ANALYZE on a table while REINDEX INDEX CONCURRENTLY is running

The following bug has been logged on the website:

Bug reference:      17848
Logged by:          Marcin Barczyński
Email address:      mba.ogolny@gmail.com
PostgreSQL version: 13.10
Operating system:   Ubuntu
Description:

In order to reproduce, first prepare the data:

DROP TABLE IF EXISTS demo;
CREATE TABLE demo(val BIGINT);
CREATE INDEX demo_idx ON demo(val);
INSERT INTO demo SELECT val FROM generate_series(1, 10000000) val;

Now, in one terminal run:

q=# REINDEX INDEX CONCURRENTLY demo_idx;

And immediately in the other:

q=# ANALYZE demo;

When REINDEX INDEX CONCURRENTLY is about to finish, it fails with:

ERROR:  deadlock detected
DETAIL:  Process 762797 waits for ShareLock on virtual transaction 4/32405;
blocked by process 752318.
Process 752318 waits for ShareUpdateExclusiveLock on relation 202300 of
database 58517; blocked by process 762797.
HINT:  See server log for query details.