From 5600fcbd4534862944237bbc5f0c31c90eee4776 Mon Sep 17 00:00:00 2001
From: Greg Lamberson <greg@lamco.io>
Date: Sun, 22 Nov 2026 14:51:15 -0600
Subject: [PATCH v1] Fix removal of two-phase state files in the future at
 recovery

At the beginning of recovery, restoreTwoPhaseData() scans pg_twophase
and ProcessTwoPhaseBuffer() rejects the files of transactions that are
already finished, or whose XID is in the future of the next XID of the
checkpoint that recovery begins with.  A rejected file was removed with
RemoveTwoPhaseFile(), which rebuilds the name of the file from the
32-bit XID and the next XID.  That conversion is only valid for an XID
that is not newer than the next XID, so for a file in the future the
name computed had the epoch before the one the file has, FFFFFFFF with
an epoch of 0.  The removal failed with a WARNING and the file was left
in place.  In assert-enabled builds, the assertion of
FullTransactionIdFromAllowableAt() failed instead and the server was
not able to start.

A file in the future does not require a manual copy of files.  It is
the normal result of two sequences, where WAL replay also includes the
PREPARE record of the transaction:
- A crash while a checkpoint is running, after CheckPointTwoPhase() has
written the file and before the control file is updated.  Recovery
begins with the previous checkpoint.
- A base backup, when a checkpoint writes the file after the checkpoint
the backup begins with and before pg_twophase is copied.

With the file left in place, PrepareRedoAdd() found it when replaying
the PREPARE record and skipped the record, assuming that the
transaction had been restored from disk.  Recovery then finished without
the prepared transaction: it was missing from pg_prepared_xacts, held no
locks, and its XID was seen as aborted, until the next restart loaded
the file.  In the meantime, reads and VACUUM could treat its changes as
dead, and other sessions could update the same rows, so a later COMMIT
PREPARED resulted in a committed transaction with part or none of its
changes, or in duplicated rows.

restoreTwoPhaseData() parses a FullTransactionId from the name of each
file.  It is now given to ProcessTwoPhaseBuffer(), and a rejected file
is removed under the name it was found with.  The other callers of
ProcessTwoPhaseBuffer() take XIDs from the entries of TwoPhaseState.
These are never newer than the next XID, as they come from files that
were accepted at the beginning of recovery or from WAL records already
replayed, so their removal path is unchanged.  Once the file is removed,
the replay of the PREPARE record rebuilds the transaction, as it does
in v16 and older versions.

This does not change which files are rejected.  The decision still
compares the 32-bit XID with the next XID and looks at pg_xact, in the
same order, so there is no new CLOG lookup.  The epoch in a file name
is used to remove that file and for nothing else.  In particular, no
file is rejected because of its epoch, which was the defect of
c3de0f9eed38, reverted by a6c70f68cdeb: a file of the previous epoch is
valid after an XID wraparound.  A file in the future across an epoch
boundary is removed under its own name as well.

v19 does not have this problem since 62a17a92833d, which changes the
signature of the two-phase callbacks and cannot be backpatched.  Here,
only static routines of twophase.c change.

The wrong file name and the leftover file were reported by Vitaly
Davydov in December 2024, in the discussion linked below.

Author: Greg Lamberson
Discussion: https://postgr.es/m/13b5b6-676c3080-4d-531db900@47931709
---
 src/backend/access/transam/twophase.c | 55 +++++++++++++++++---
 src/test/recovery/t/009_twophase.pl   | 74 +++++++++++++++++++++++++++
 2 files changed, 123 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/transam/twophase.c b/src/backend/access/transam/twophase.c
index 0531f89a8fe..b9087af8a3c 100644
--- a/src/backend/access/transam/twophase.c
+++ b/src/backend/access/transam/twophase.c
@@ -223,12 +223,15 @@ static void RemoveGXact(GlobalTransaction gxact);
 
 static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len);
 static char *ProcessTwoPhaseBuffer(TransactionId xid,
+								   FullTransactionId fxid,
 								   XLogRecPtr prepare_start_lsn,
 								   bool fromdisk, bool setParent, bool setNextXid);
 static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid,
 								const char *gid, TimestampTz prepared_at, Oid owner,
 								Oid databaseid);
 static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning);
+static void RemoveRejectedTwoPhaseFile(TransactionId xid,
+									   FullTransactionId fxid);
 static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len);
 
 /*
@@ -1718,6 +1721,40 @@ RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
 					 errmsg("could not remove file \"%s\": %m", path)));
 }
 
+/*
+ * Remove a 2PC file rejected by ProcessTwoPhaseBuffer().
+ *
+ * A file found by restoreTwoPhaseData() while scanning pg_twophase comes
+ * with the FullTransactionId parsed from its name, and is removed under
+ * that name.  RemoveTwoPhaseFile() cannot be used for it, as it rebuilds
+ * the name of the file from the next XID.  That does not work for a file in
+ * the future, whose XID is outside the range that
+ * FullTransactionIdFromAllowableAt() supports: the name computed would have
+ * the wrong epoch, and the file would be left behind.
+ *
+ * Without a valid FullTransactionId, the XID comes from an entry of
+ * TwoPhaseState, and RemoveTwoPhaseFile() is used.
+ */
+static void
+RemoveRejectedTwoPhaseFile(TransactionId xid, FullTransactionId fxid)
+{
+	char		path[MAXPGPATH];
+
+	if (!FullTransactionIdIsValid(fxid))
+	{
+		RemoveTwoPhaseFile(xid, true);
+		return;
+	}
+
+	snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X%08X",
+			 EpochFromFullTransactionId(fxid),
+			 XidFromFullTransactionId(fxid));
+	if (unlink(path))
+		ereport(WARNING,
+				(errcode_for_file_access(),
+				 errmsg("could not remove file \"%s\": %m", path)));
+}
+
 /*
  * Recreates a state file. This is used in WAL replay and during
  * checkpoint creation.
@@ -1933,7 +1970,7 @@ restoreTwoPhaseData(void)
 			fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
 			xid = XidFromFullTransactionId(fxid);
 
-			buf = ProcessTwoPhaseBuffer(xid, InvalidXLogRecPtr,
+			buf = ProcessTwoPhaseBuffer(xid, fxid, InvalidXLogRecPtr,
 										true, false, false);
 			if (buf == NULL)
 				continue;
@@ -1999,7 +2036,7 @@ PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
 
 		xid = gxact->xid;
 
-		buf = ProcessTwoPhaseBuffer(xid,
+		buf = ProcessTwoPhaseBuffer(xid, InvalidFullTransactionId,
 									gxact->prepare_start_lsn,
 									gxact->ondisk, false, true);
 
@@ -2073,7 +2110,7 @@ StandbyRecoverPreparedTransactions(void)
 
 		xid = gxact->xid;
 
-		buf = ProcessTwoPhaseBuffer(xid,
+		buf = ProcessTwoPhaseBuffer(xid, InvalidFullTransactionId,
 									gxact->prepare_start_lsn,
 									gxact->ondisk, true, false);
 		if (buf != NULL)
@@ -2125,7 +2162,7 @@ RecoverPreparedTransactions(void)
 		 * SubTransSetParent has been set before, if the prepared transaction
 		 * generated xid assignment records.
 		 */
-		buf = ProcessTwoPhaseBuffer(xid,
+		buf = ProcessTwoPhaseBuffer(xid, InvalidFullTransactionId,
 									gxact->prepare_start_lsn,
 									gxact->ondisk, true, false);
 		if (buf == NULL)
@@ -2196,6 +2233,11 @@ RecoverPreparedTransactions(void)
  * Given a transaction id, read it either from disk or read it directly
  * via shmem xlog record pointer using the provided "prepare_start_lsn".
  *
+ * "fxid" is the FullTransactionId parsed from the name of the file when the
+ * transaction id comes from a scan of pg_twophase, so as a file rejected
+ * here is removed under the name it was found with.  It is
+ * InvalidFullTransactionId when the transaction id comes from shared memory.
+ *
  * If setParent is true, set up subtransaction parent linkages.
  *
  * If setNextXid is true, set TransamVariables->nextXid to the newest
@@ -2203,6 +2245,7 @@ RecoverPreparedTransactions(void)
  */
 static char *
 ProcessTwoPhaseBuffer(TransactionId xid,
+					  FullTransactionId fxid,
 					  XLogRecPtr prepare_start_lsn,
 					  bool fromdisk,
 					  bool setParent, bool setNextXid)
@@ -2227,7 +2270,7 @@ ProcessTwoPhaseBuffer(TransactionId xid,
 			ereport(WARNING,
 					(errmsg("removing stale two-phase state file for transaction %u",
 							xid)));
-			RemoveTwoPhaseFile(xid, true);
+			RemoveRejectedTwoPhaseFile(xid, fxid);
 		}
 		else
 		{
@@ -2247,7 +2290,7 @@ ProcessTwoPhaseBuffer(TransactionId xid,
 			ereport(WARNING,
 					(errmsg("removing future two-phase state file for transaction %u",
 							xid)));
-			RemoveTwoPhaseFile(xid, true);
+			RemoveRejectedTwoPhaseFile(xid, fxid);
 		}
 		else
 		{
diff --git a/src/test/recovery/t/009_twophase.pl b/src/test/recovery/t/009_twophase.pl
index 6cd65ae91b5..a04718d6f77 100644
--- a/src/test/recovery/t/009_twophase.pl
+++ b/src/test/recovery/t/009_twophase.pl
@@ -5,6 +5,7 @@
 use strict;
 use warnings FATAL => 'all';
 
+use File::Copy qw(copy);
 use PostgreSQL::Test::Cluster;
 use PostgreSQL::Test::Utils;
 use Test::More;
@@ -572,4 +573,77 @@ my $nsubtrans = $cur_primary->safe_psql('postgres',
 );
 isnt($osubtrans, $nsubtrans, "contents of pg_subtrans/ have changed");
 
+###############################################################################
+# Check recovery with a two-phase state file newer than the checkpoint that
+# recovery starts from.
+#
+# A crash after a checkpoint has written the state file of a prepared
+# transaction and before the control file is updated leaves in pg_twophase a
+# file whose transaction ID is newer than the next transaction ID of the
+# previous checkpoint, which is where recovery starts.  A base backup can
+# include the same state.  It is produced here by putting back the control
+# file saved before the checkpoint that writes the state file.  Recovery has
+# to remove the file, and rebuild the prepared transaction from WAL.
+###############################################################################
+
+# Switch to a new WAL segment first, so as the second checkpoint does not
+# recycle the segment that includes the redo point of the first one.
+$cur_primary->safe_psql('postgres', "SELECT pg_switch_wal(); CHECKPOINT;");
+my $control_file = $cur_primary->data_dir . '/global/pg_control';
+my $control_file_saved = $cur_primary->basedir . '/pg_control.saved';
+copy($control_file, $control_file_saved)
+  or die "could not copy $control_file: $!";
+
+# Consume some transaction IDs, so as the transaction prepared next has a
+# transaction ID newer than the next transaction ID of the checkpoint above.
+$cur_primary->safe_psql('postgres',
+	"INSERT INTO t_009_tbl VALUES (28, 'issued before prepare')");
+$cur_primary->safe_psql('postgres',
+	"INSERT INTO t_009_tbl VALUES (29, 'issued before prepare')");
+$cur_primary->safe_psql(
+	'postgres', "
+	BEGIN;
+	INSERT INTO t_009_tbl VALUES (30, 'issued in future file');
+	PREPARE TRANSACTION 'xact_009_future';");
+my $twophase_files = $cur_primary->safe_psql('postgres',
+	"SELECT count(*) FROM pg_ls_dir('pg_twophase')");
+$cur_primary->safe_psql('postgres', "CHECKPOINT");
+isnt(
+	$cur_primary->safe_psql(
+		'postgres', "SELECT count(*) FROM pg_ls_dir('pg_twophase')"),
+	$twophase_files,
+	"two-phase state file written by checkpoint");
+
+$cur_primary->stop('immediate');
+copy($control_file_saved, $control_file)
+  or die "could not copy $control_file_saved: $!";
+my $log_offset = -s $cur_primary->logfile;
+$cur_primary->start;
+
+ok( $cur_primary->log_contains(
+		qr/removing future two-phase state file for transaction/, $log_offset
+	),
+	"future two-phase state file detected at recovery");
+ok(!$cur_primary->log_contains(qr/could not remove file/, $log_offset),
+	"future two-phase state file removed at recovery");
+
+$cur_primary->psql(
+	'postgres',
+	"SELECT count(*) FROM pg_prepared_xacts WHERE gid = 'xact_009_future'",
+	stdout => \$psql_out);
+is($psql_out, '1',
+	"Prepared transaction of future two-phase state file is recovered");
+
+$psql_rc =
+  $cur_primary->psql('postgres', "COMMIT PREPARED 'xact_009_future'");
+is($psql_rc, '0',
+	"Commit prepared transaction of future two-phase state file");
+
+$cur_primary->psql(
+	'postgres',
+	"SELECT count(*) FROM t_009_tbl WHERE id = 30",
+	stdout => \$psql_out);
+is($psql_out, '1',
+	"Committed data of future two-phase state file is visible");
+
 done_testing();
-- 
2.47.3

