Skip to content

Commit cf4401f

Browse files
committed
Fix race condition in COMMIT PREPARED causing orphaned 2PC files
COMMIT PREPARED removes on-disk 2PC files near its end, but the state checked if a file is on-disk or not gets read from shared memory while not holding the two-phase state lock. Because of that, there was a small window where a second backend doing a PREPARE TRANSACTION could reuse the GlobalTransaction put back into the 2PC free list by the COMMIT PREPARED, overwriting the "ondisk" flag read afterwards by the COMMIT PREPARED to decide if its on-disk two-phase state file should be removed, preventing the file deletion. This commit fixes this issue so as the "ondisk" flag in the GlobalTransaction is read while holding the two-phase state lock, not from shared memory after its entry has been added to the free list. Orphaned two-phase state files flushed to disk after a checkpoint are discarded at the beginning of recovery. However, a truncation of pg_xact/ would make the startup process issue a FATAL when it cannot read the SLRU page holding the state of the transaction whose 2PC file was orphaned, which is a necessary step to decide if the 2PC file should be removed or not. Removing manually the file would be necessary in this case. Issue introduced by effe7d9, so backpatch all the way down. Mea culpa. Author: wuchengwen Discussion: https://postgr.es/m/[email protected] Backpatch-through: 12
1 parent 3b1a377 commit cf4401f

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

src/backend/access/transam/twophase.c

+8-1
Original file line numberDiff line numberDiff line change
@@ -1505,6 +1505,7 @@ FinishPreparedTransaction(const char *gid, bool isCommit)
15051505
GlobalTransaction gxact;
15061506
PGPROC *proc;
15071507
TransactionId xid;
1508+
bool ondisk;
15081509
char *buf;
15091510
char *bufptr;
15101511
TwoPhaseFileHeader *hdr;
@@ -1657,6 +1658,12 @@ FinishPreparedTransaction(const char *gid, bool isCommit)
16571658

16581659
PredicateLockTwoPhaseFinish(xid, isCommit);
16591660

1661+
/*
1662+
* Read this value while holding the two-phase lock, as the on-disk 2PC
1663+
* file is physically removed after the lock is released.
1664+
*/
1665+
ondisk = gxact->ondisk;
1666+
16601667
/* Clear shared memory state */
16611668
RemoveGXact(gxact);
16621669

@@ -1672,7 +1679,7 @@ FinishPreparedTransaction(const char *gid, bool isCommit)
16721679
/*
16731680
* And now we can clean up any files we may have left.
16741681
*/
1675-
if (gxact->ondisk)
1682+
if (ondisk)
16761683
RemoveTwoPhaseFile(xid, true);
16771684

16781685
MyLockedGxact = NULL;

0 commit comments

Comments
 (0)