Skip to content

Commit 0dcff75

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 fe1d8c1 commit 0dcff75

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
@@ -141,6 +141,7 @@ DefineIndex(RangeVar *heapRelation,
141141
int16 *coloptions;
142142
IndexInfo *indexInfo;
143143
int numberOfAttributes;
144+
TransactionId limitXmin;
144145
VirtualTransactionId *old_lockholders;
145146
VirtualTransactionId *old_snapshots;
146147
int n_old_snapshots;
@@ -640,6 +641,18 @@ DefineIndex(RangeVar *heapRelation,
640641
*/
641642
validate_index(relationId, indexRelationId, snapshot);
642643

644+
/*
645+
* Drop the reference snapshot. We must do this before waiting out other
646+
* snapshot holders, else we will deadlock against other processes also
647+
* doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
648+
* they must wait for. But first, save the snapshot's xmin to use as
649+
* limitXmin for GetCurrentVirtualXIDs().
650+
*/
651+
limitXmin = snapshot->xmin;
652+
653+
PopActiveSnapshot();
654+
UnregisterSnapshot(snapshot);
655+
643656
/*
644657
* The index is now valid in the sense that it contains all currently
645658
* interesting tuples. But since it might not contain tuples deleted just
@@ -672,7 +685,7 @@ DefineIndex(RangeVar *heapRelation,
672685
* GetCurrentVirtualXIDs. If, during any iteration, a particular vxid
673686
* doesn't show up in the output, we know we can forget about it.
674687
*/
675-
old_snapshots = GetCurrentVirtualXIDs(snapshot->xmin, true, false,
688+
old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
676689
PROC_IS_AUTOVACUUM | PROC_IN_VACUUM,
677690
&n_old_snapshots);
678691

@@ -689,7 +702,7 @@ DefineIndex(RangeVar *heapRelation,
689702
int j;
690703
int k;
691704

692-
newer_snapshots = GetCurrentVirtualXIDs(snapshot->xmin,
705+
newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
693706
true, false,
694707
PROC_IS_AUTOVACUUM | PROC_IN_VACUUM,
695708
&n_newer_snapshots);
@@ -728,12 +741,6 @@ DefineIndex(RangeVar *heapRelation,
728741
*/
729742
CacheInvalidateRelcacheByRelid(heaprelid.relId);
730743

731-
/* we can now do away with our active snapshot */
732-
PopActiveSnapshot();
733-
734-
/* And we can remove the validating snapshot too */
735-
UnregisterSnapshot(snapshot);
736-
737744
/*
738745
* Last thing to do is release the session-level lock on the parent table.
739746
*/

0 commit comments

Comments
 (0)