Skip to content

Commit 9e859a9

Browse files
committed
Avoid deadlock between concurrent CREATE INDEX CONCURRENTLY commands.
There was a high probability of two or more concurrent C.I.C. commands deadlocking just before completion, because each would wait for the others to release their reference snapshots. Fix by releasing the snapshot before waiting for other snapshots to go away. Per report from Paul Hinze. Back-patch to all active branches.
1 parent 719845b commit 9e859a9

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/backend/commands/indexcmds.c

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,7 @@ DefineIndex(IndexStmt *stmt,
319319
int16 *coloptions;
320320
IndexInfo *indexInfo;
321321
int numberOfAttributes;
322+
TransactionId limitXmin;
322323
VirtualTransactionId *old_lockholders;
323324
VirtualTransactionId *old_snapshots;
324325
int n_old_snapshots;
@@ -769,6 +770,18 @@ DefineIndex(IndexStmt *stmt,
769770
*/
770771
validate_index(relationId, indexRelationId, snapshot);
771772

773+
/*
774+
* Drop the reference snapshot. We must do this before waiting out other
775+
* snapshot holders, else we will deadlock against other processes also
776+
* doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
777+
* they must wait for. But first, save the snapshot's xmin to use as
778+
* limitXmin for GetCurrentVirtualXIDs().
779+
*/
780+
limitXmin = snapshot->xmin;
781+
782+
PopActiveSnapshot();
783+
UnregisterSnapshot(snapshot);
784+
772785
/*
773786
* The index is now valid in the sense that it contains all currently
774787
* interesting tuples. But since it might not contain tuples deleted just
@@ -801,7 +814,7 @@ DefineIndex(IndexStmt *stmt,
801814
* GetCurrentVirtualXIDs. If, during any iteration, a particular vxid
802815
* doesn't show up in the output, we know we can forget about it.
803816
*/
804-
old_snapshots = GetCurrentVirtualXIDs(snapshot->xmin, true, false,
817+
old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
805818
PROC_IS_AUTOVACUUM | PROC_IN_VACUUM,
806819
&n_old_snapshots);
807820

@@ -818,7 +831,7 @@ DefineIndex(IndexStmt *stmt,
818831
int j;
819832
int k;
820833

821-
newer_snapshots = GetCurrentVirtualXIDs(snapshot->xmin,
834+
newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
822835
true, false,
823836
PROC_IS_AUTOVACUUM | PROC_IN_VACUUM,
824837
&n_newer_snapshots);
@@ -857,12 +870,6 @@ DefineIndex(IndexStmt *stmt,
857870
*/
858871
CacheInvalidateRelcacheByRelid(heaprelid.relId);
859872

860-
/* we can now do away with our active snapshot */
861-
PopActiveSnapshot();
862-
863-
/* And we can remove the validating snapshot too */
864-
UnregisterSnapshot(snapshot);
865-
866873
/*
867874
* Last thing to do is release the session-level lock on the parent table.
868875
*/

0 commit comments

Comments
 (0)