]> granicus.if.org Git - postgresql/blobdiff - src/backend/storage/lmgr/predicate.c
Update copyright for 2014
[postgresql] / src / backend / storage / lmgr / predicate.c
index 02f5d033b28d131e6c0769aa1745d71b24ee320b..633b37de59e23c9f2fc954c2d26f50b72926c3e0 100644 (file)
  *             - Protects both PredXact and SerializableXidHash.
  *
  *
- * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
  *             PageIsPredicateLocked(Relation relation, BlockNumber blkno)
  *
  * predicate lock maintenance
- *             RegisterSerializableTransaction(Snapshot snapshot)
+ *             GetSerializableTransactionSnapshot(Snapshot snapshot)
+ *             SetSerializableTransactionSnapshot(Snapshot snapshot,
+ *                                                                                TransactionId sourcexid)
  *             RegisterPredicateLockingXid(void)
- *             PredicateLockRelation(Relation relation)
- *             PredicateLockPage(Relation relation, BlockNumber blkno)
- *             PredicateLockTuple(Relation relation, HeapTuple tuple)
+ *             PredicateLockRelation(Relation relation, Snapshot snapshot)
+ *             PredicateLockPage(Relation relation, BlockNumber blkno,
+ *                                             Snapshot snapshot)
+ *             PredicateLockTuple(Relation relation, HeapTuple tuple,
+ *                                             Snapshot snapshot)
  *             PredicateLockPageSplit(Relation relation, BlockNumber oldblkno,
- *                                                        BlockNumber newblkno);
+ *                                                        BlockNumber newblkno)
  *             PredicateLockPageCombine(Relation relation, BlockNumber oldblkno,
- *                                                              BlockNumber newblkno);
+ *                                                              BlockNumber newblkno)
  *             TransferPredicateLocksToHeapRelation(Relation relation)
  *             ReleasePredicateLocks(bool isCommit)
  *
  * conflict detection (may also trigger rollback)
  *             CheckForSerializableConflictOut(bool visible, Relation relation,
- *                                                                             HeapTupleData *tup, Buffer buffer)
+ *                                                                             HeapTupleData *tup, Buffer buffer,
+ *                                                                             Snapshot snapshot)
  *             CheckForSerializableConflictIn(Relation relation, HeapTupleData *tup,
  *                                                                        Buffer buffer)
  *             CheckTableForSerializableConflictIn(Relation relation)
 
 #include "postgres.h"
 
+#include "access/htup_details.h"
 #include "access/slru.h"
 #include "access/subtrans.h"
 #include "access/transam.h"
 #include "storage/bufmgr.h"
 #include "storage/predicate.h"
 #include "storage/predicate_internals.h"
+#include "storage/proc.h"
 #include "storage/procarray.h"
 #include "utils/rel.h"
 #include "utils/snapmgr.h"
 
 #define SxactIsOnFinishedList(sxact) (!SHMQueueIsDetached(&((sxact)->finishedLink)))
 
-#define SxactIsPrepared(sxact) (((sxact)->flags & SXACT_FLAG_PREPARED) != 0)
+/*
+ * Note that a sxact is marked "prepared" once it has passed
+ * PreCommit_CheckForSerializationFailure, even if it isn't using
+ * 2PC. This is the point at which it can no longer be aborted.
+ *
+ * The PREPARED flag remains set after commit, so SxactIsCommitted
+ * implies SxactIsPrepared.
+ */
 #define SxactIsCommitted(sxact) (((sxact)->flags & SXACT_FLAG_COMMITTED) != 0)
+#define SxactIsPrepared(sxact) (((sxact)->flags & SXACT_FLAG_PREPARED) != 0)
 #define SxactIsRolledBack(sxact) (((sxact)->flags & SXACT_FLAG_ROLLED_BACK) != 0)
+#define SxactIsDoomed(sxact) (((sxact)->flags & SXACT_FLAG_DOOMED) != 0)
 #define SxactIsReadOnly(sxact) (((sxact)->flags & SXACT_FLAG_READ_ONLY) != 0)
 #define SxactHasSummaryConflictIn(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_IN) != 0)
 #define SxactHasSummaryConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_OUT) != 0)
 #define SxactIsDeferrableWaiting(sxact) (((sxact)->flags & SXACT_FLAG_DEFERRABLE_WAITING) != 0)
 #define SxactIsROSafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_SAFE) != 0)
 #define SxactIsROUnsafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_UNSAFE) != 0)
-#define SxactIsMarkedForDeath(sxact) (((sxact)->flags & SXACT_FLAG_MARKED_FOR_DEATH) != 0)
-
-/*
- * Is this relation exempt from predicate locking? We don't do predicate
- * locking on system or temporary relations.
- */
-#define SkipPredicateLocksForRelation(relation) \
-       (((relation)->rd_id < FirstBootstrapObjectId) \
-       || RelationUsesLocalBuffers(relation))
-
-/*
- * When a public interface method is called for serializing a relation within
- * the current transaction, this is the test to see if we should do a quick
- * return.
- */
-#define SkipSerialization(relation) \
-       ((!IsolationIsSerializable()) \
-       || ((MySerializableXact == InvalidSerializableXact)) \
-       || ReleasePredicateLocksIfROSafe() \
-       || SkipPredicateLocksForRelation(relation))
-
 
 /*
  * Compute the hash code associated with a PREDICATELOCKTARGETTAG.
@@ -314,7 +309,13 @@ static SlruCtlData OldSerXidSlruCtlData;
 #define OLDSERXID_PAGESIZE                     BLCKSZ
 #define OLDSERXID_ENTRYSIZE                    sizeof(SerCommitSeqNo)
 #define OLDSERXID_ENTRIESPERPAGE       (OLDSERXID_PAGESIZE / OLDSERXID_ENTRYSIZE)
-#define OLDSERXID_MAX_PAGE                     (SLRU_PAGES_PER_SEGMENT * 0x10000 - 1)
+
+/*
+ * Set maximum pages based on the lesser of the number needed to track all
+ * transactions and the maximum that SLRU supports.
+ */
+#define OLDSERXID_MAX_PAGE                     Min(SLRU_PAGES_PER_SEGMENT * 0x10000 - 1, \
+                                                                               (MaxTransactionId) / OLDSERXID_ENTRIESPERPAGE)
 
 #define OldSerXidNextPage(page) (((page) >= OLDSERXID_MAX_PAGE) ? 0 : (page) + 1)
 
@@ -380,7 +381,7 @@ static SHM_QUEUE *FinishedSerializableTransactions;
  * this entry, you can ensure that there's enough scratch space available for
  * inserting one entry in the hash table. This is an otherwise-invalid tag.
  */
-static const PREDICATELOCKTARGETTAG ScratchTargetTag = {0, 0, 0, 0, 0};
+static const PREDICATELOCKTARGETTAG ScratchTargetTag = {0, 0, 0, 0};
 static uint32 ScratchTargetTagHash;
 static int     ScratchPartitionLock;
 
@@ -420,7 +421,8 @@ static void OldSerXidSetActiveSerXmin(TransactionId xid);
 static uint32 predicatelock_hash(const void *key, Size keysize);
 static void SummarizeOldestCommittedSxact(void);
 static Snapshot GetSafeSnapshot(Snapshot snapshot);
-static Snapshot RegisterSerializableTransactionInt(Snapshot snapshot);
+static Snapshot GetSerializableTransactionSnapshotInt(Snapshot snapshot,
+                                                                         TransactionId sourcexid);
 static bool PredicateLockExists(const PREDICATELOCKTARGETTAG *targettag);
 static bool GetParentPredicateLockTag(const PREDICATELOCKTARGETTAG *tag,
                                                  PREDICATELOCKTARGETTAG *parent);
@@ -437,14 +439,13 @@ static void CreatePredicateLock(const PREDICATELOCKTARGETTAG *targettag,
                                        uint32 targettaghash,
                                        SERIALIZABLEXACT *sxact);
 static void DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash);
-static bool TransferPredicateLocksToNewTarget(const PREDICATELOCKTARGETTAG oldtargettag,
-                                                                 const PREDICATELOCKTARGETTAG newtargettag,
+static bool TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag,
+                                                                 PREDICATELOCKTARGETTAG newtargettag,
                                                                  bool removeOld);
 static void PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag);
-static void DropAllPredicateLocksFromTable(const Relation relation,
+static void DropAllPredicateLocksFromTable(Relation relation,
                                                           bool transfer);
 static void SetNewSxactGlobalXmin(void);
-static bool ReleasePredicateLocksIfROSafe(void);
 static void ClearOldPredicateLocks(void);
 static void ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
                                                   bool summarize);
@@ -454,6 +455,91 @@ static void FlagRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer);
 static void OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
                                                                                SERIALIZABLEXACT *writer);
 
+
+/*------------------------------------------------------------------------*/
+
+/*
+ * Does this relation participate in predicate locking? Temporary and system
+ * relations are exempt, as are materialized views.
+ */
+static inline bool
+PredicateLockingNeededForRelation(Relation relation)
+{
+       return !(relation->rd_id < FirstBootstrapObjectId ||
+                        RelationUsesLocalBuffers(relation) ||
+                        relation->rd_rel->relkind == RELKIND_MATVIEW);
+}
+
+/*
+ * When a public interface method is called for a read, this is the test to
+ * see if we should do a quick return.
+ *
+ * Note: this function has side-effects! If this transaction has been flagged
+ * as RO-safe since the last call, we release all predicate locks and reset
+ * MySerializableXact. That makes subsequent calls to return quickly.
+ *
+ * This is marked as 'inline' to make to eliminate the function call overhead
+ * in the common case that serialization is not needed.
+ */
+static inline bool
+SerializationNeededForRead(Relation relation, Snapshot snapshot)
+{
+       /* Nothing to do if this is not a serializable transaction */
+       if (MySerializableXact == InvalidSerializableXact)
+               return false;
+
+       /*
+        * Don't acquire locks or conflict when scanning with a special snapshot.
+        * This excludes things like CLUSTER and REINDEX. They use the wholesale
+        * functions TransferPredicateLocksToHeapRelation() and
+        * CheckTableForSerializableConflictIn() to participate serialization, but
+        * the scans involved don't need serialization.
+        */
+       if (!IsMVCCSnapshot(snapshot))
+               return false;
+
+       /*
+        * Check if we have just become "RO-safe". If we have, immediately release
+        * all locks as they're not needed anymore. This also resets
+        * MySerializableXact, so that subsequent calls to this function can exit
+        * quickly.
+        *
+        * A transaction is flagged as RO_SAFE if all concurrent R/W transactions
+        * commit without having conflicts out to an earlier snapshot, thus
+        * ensuring that no conflicts are possible for this transaction.
+        */
+       if (SxactIsROSafe(MySerializableXact))
+       {
+               ReleasePredicateLocks(false);
+               return false;
+       }
+
+       /* Check if the relation doesn't participate in predicate locking */
+       if (!PredicateLockingNeededForRelation(relation))
+               return false;
+
+       return true;                            /* no excuse to skip predicate locking */
+}
+
+/*
+ * Like SerializationNeededForRead(), but called on writes.
+ * The logic is the same, but there is no snapshot and we can't be RO-safe.
+ */
+static inline bool
+SerializationNeededForWrite(Relation relation)
+{
+       /* Nothing to do if this is not a serializable transaction */
+       if (MySerializableXact == InvalidSerializableXact)
+               return false;
+
+       /* Check if the relation doesn't participate in predicate locking */
+       if (!PredicateLockingNeededForRelation(relation))
+               return false;
+
+       return true;                            /* no excuse to skip predicate locking */
+}
+
+
 /*------------------------------------------------------------------------*/
 
 /*
@@ -542,8 +628,8 @@ RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer)
        Assert(reader != writer);
 
        /* Check the ends of the purported conflict first. */
-       if (SxactIsRolledBack(reader)
-               || SxactIsRolledBack(writer)
+       if (SxactIsDoomed(reader)
+               || SxactIsDoomed(writer)
                || SHMQueueEmpty(&reader->outConflicts)
                || SHMQueueEmpty(&writer->inConflicts))
                return false;
@@ -582,7 +668,7 @@ SetRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
        if (!conflict)
                ereport(ERROR,
                                (errcode(ERRCODE_OUT_OF_MEMORY),
-                                errmsg("not enough elements in RWConflictPool to record a rw-conflict"),
+                                errmsg("not enough elements in RWConflictPool to record a read/write conflict"),
                                 errhint("You might need to run fewer transactions at a time or increase max_connections.")));
 
        SHMQueueDelete(&conflict->outLink);
@@ -610,7 +696,7 @@ SetPossibleUnsafeConflict(SERIALIZABLEXACT *roXact,
        if (!conflict)
                ereport(ERROR,
                                (errcode(ERRCODE_OUT_OF_MEMORY),
-                                errmsg("not enough elements in RWConflictPool to record a potential rw-conflict"),
+                                errmsg("not enough elements in RWConflictPool to record a potential read/write conflict"),
                                 errhint("You might need to run fewer transactions at a time or increase max_connections.")));
 
        SHMQueueDelete(&conflict->outLink);
@@ -687,7 +773,7 @@ OldSerXidPagePrecedesLogically(int p, int q)
        diff = p - q;
        if (diff >= ((OLDSERXID_MAX_PAGE + 1) / 2))
                diff -= OLDSERXID_MAX_PAGE + 1;
-       else if (diff < -((OLDSERXID_MAX_PAGE + 1) / 2))
+       else if (diff < -((int) (OLDSERXID_MAX_PAGE + 1) / 2))
                diff += OLDSERXID_MAX_PAGE + 1;
        return diff < 0;
 }
@@ -816,7 +902,7 @@ OldSerXidAdd(TransactionId xid, SerCommitSeqNo minConflictCommitSeqNo)
                        oldSerXidControl->warningIssued = true;
                        ereport(WARNING,
                                        (errmsg("memory for serializable conflict tracking is nearly exhausted"),
-                                        errhint("There may be an idle transaction or a forgotten prepared transaction causing this.")));
+                                        errhint("There might be an idle transaction or a forgotten prepared transaction causing this.")));
                }
        }
 
@@ -1110,6 +1196,7 @@ InitPredicateLocks(void)
                }
                PredXact->OldCommittedSxact = CreatePredXact();
                SetInvalidVirtualTransactionId(PredXact->OldCommittedSxact->vxid);
+               PredXact->OldCommittedSxact->prepareSeqNo = 0;
                PredXact->OldCommittedSxact->commitSeqNo = 0;
                PredXact->OldCommittedSxact->SeqNo.lastCommitBeforeSnapshot = 0;
                SHMQueueInit(&PredXact->OldCommittedSxact->outConflicts);
@@ -1150,7 +1237,7 @@ InitPredicateLocks(void)
         * that this will prevent resource exhaustion in even the most pessimal
         * loads up to max_connections = 200 with all 200 connections pounding the
         * database with serializable transactions.  Beyond that, there may be
-        * occassional transactions canceled when trying to flag conflicts. That's
+        * occasional transactions canceled when trying to flag conflicts. That's
         * probably OK.
         */
        max_table_size *= 5;
@@ -1404,6 +1491,10 @@ SummarizeOldestCommittedSxact(void)
  *             without further checks. This requires waiting for concurrent
  *             transactions to complete, and retrying with a new snapshot if
  *             one of them could possibly create a conflict.
+ *
+ *             As with GetSerializableTransactionSnapshot (which this is a subroutine
+ *             for), the passed-in Snapshot pointer should reference a static data
+ *             area that can safely be passed to GetSnapshotData.
  */
 static Snapshot
 GetSafeSnapshot(Snapshot origSnapshot)
@@ -1415,12 +1506,13 @@ GetSafeSnapshot(Snapshot origSnapshot)
        while (true)
        {
                /*
-                * RegisterSerializableTransactionInt is going to call
-                * GetSnapshotData, so we need to provide it the static snapshot our
-                * caller passed to us. It returns a copy of that snapshot and
-                * registers it on TopTransactionResourceOwner.
+                * GetSerializableTransactionSnapshotInt is going to call
+                * GetSnapshotData, so we need to provide it the static snapshot area
+                * our caller passed to us.  The pointer returned is actually the same
+                * one passed to it, but we avoid assuming that here.
                 */
-               snapshot = RegisterSerializableTransactionInt(origSnapshot);
+               snapshot = GetSerializableTransactionSnapshotInt(origSnapshot,
+                                                                                                          InvalidTransactionId);
 
                if (MySerializableXact == InvalidSerializableXact)
                        return snapshot;        /* no concurrent r/w xacts; it's safe */
@@ -1454,8 +1546,6 @@ GetSafeSnapshot(Snapshot origSnapshot)
                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                 errmsg("deferrable snapshot was unsafe; trying a new one")));
                ReleasePredicateLocks(false);
-               UnregisterSnapshotFromOwner(snapshot,
-                                                                       TopTransactionResourceOwner);
        }
 
        /*
@@ -1468,28 +1558,88 @@ GetSafeSnapshot(Snapshot origSnapshot)
 }
 
 /*
- * Acquire and register a snapshot which can be used for this transaction..
+ * Acquire a snapshot that can be used for the current transaction.
+ *
  * Make sure we have a SERIALIZABLEXACT reference in MySerializableXact.
  * It should be current for this process and be contained in PredXact.
+ *
+ * The passed-in Snapshot pointer should reference a static data area that
+ * can safely be passed to GetSnapshotData.  The return value is actually
+ * always this same pointer; no new snapshot data structure is allocated
+ * within this function.
  */
 Snapshot
-RegisterSerializableTransaction(Snapshot snapshot)
+GetSerializableTransactionSnapshot(Snapshot snapshot)
 {
        Assert(IsolationIsSerializable());
 
+       /*
+        * Can't use serializable mode while recovery is still active, as it is,
+        * for example, on a hot standby.  We could get here despite the check in
+        * check_XactIsoLevel() if default_transaction_isolation is set to
+        * serializable, so phrase the hint accordingly.
+        */
+       if (RecoveryInProgress())
+               ereport(ERROR,
+                               (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                errmsg("cannot use serializable mode in a hot standby"),
+                                errdetail("\"default_transaction_isolation\" is set to \"serializable\"."),
+                                errhint("You can use \"SET default_transaction_isolation = 'repeatable read'\" to change the default.")));
+
        /*
         * A special optimization is available for SERIALIZABLE READ ONLY
         * DEFERRABLE transactions -- we can wait for a suitable snapshot and
-        * thereby avoid all SSI overhead once it's running..
+        * thereby avoid all SSI overhead once it's running.
         */
        if (XactReadOnly && XactDeferrable)
                return GetSafeSnapshot(snapshot);
 
-       return RegisterSerializableTransactionInt(snapshot);
+       return GetSerializableTransactionSnapshotInt(snapshot,
+                                                                                                InvalidTransactionId);
 }
 
+/*
+ * Import a snapshot to be used for the current transaction.
+ *
+ * This is nearly the same as GetSerializableTransactionSnapshot, except that
+ * we don't take a new snapshot, but rather use the data we're handed.
+ *
+ * The caller must have verified that the snapshot came from a serializable
+ * transaction; and if we're read-write, the source transaction must not be
+ * read-only.
+ */
+void
+SetSerializableTransactionSnapshot(Snapshot snapshot,
+                                                                  TransactionId sourcexid)
+{
+       Assert(IsolationIsSerializable());
+
+       /*
+        * We do not allow SERIALIZABLE READ ONLY DEFERRABLE transactions to
+        * import snapshots, since there's no way to wait for a safe snapshot when
+        * we're using the snap we're told to.  (XXX instead of throwing an error,
+        * we could just ignore the XactDeferrable flag?)
+        */
+       if (XactReadOnly && XactDeferrable)
+               ereport(ERROR,
+                               (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                errmsg("a snapshot-importing transaction must not be READ ONLY DEFERRABLE")));
+
+       (void) GetSerializableTransactionSnapshotInt(snapshot, sourcexid);
+}
+
+/*
+ * Guts of GetSerializableTransactionSnapshot
+ *
+ * If sourcexid is valid, this is actually an import operation and we should
+ * skip calling GetSnapshotData, because the snapshot contents are already
+ * loaded up.  HOWEVER: to avoid race conditions, we must check that the
+ * source xact is still running after we acquire SerializableXactHashLock.
+ * We do that by calling ProcArrayInstallImportedXmin.
+ */
 static Snapshot
-RegisterSerializableTransactionInt(Snapshot snapshot)
+GetSerializableTransactionSnapshotInt(Snapshot snapshot,
+                                                                         TransactionId sourcexid)
 {
        PGPROC     *proc;
        VirtualTransactionId vxid;
@@ -1509,6 +1659,14 @@ RegisterSerializableTransactionInt(Snapshot snapshot)
        /*
         * First we get the sxact structure, which may involve looping and access
         * to the "finished" list to free a structure for use.
+        *
+        * We must hold SerializableXactHashLock when taking/checking the snapshot
+        * to avoid race conditions, for much the same reasons that
+        * GetSnapshotData takes the ProcArrayLock.  Since we might have to
+        * release SerializableXactHashLock to call SummarizeOldestCommittedSxact,
+        * this means we have to create the sxact first, which is a bit annoying
+        * (in particular, an elog(ERROR) in procarray.c would cause us to leak
+        * the sxact).  Consider refactoring to avoid this.
         */
 #ifdef TEST_OLDSERXID
        SummarizeOldestCommittedSxact();
@@ -1526,9 +1684,19 @@ RegisterSerializableTransactionInt(Snapshot snapshot)
                }
        } while (!sxact);
 
-       /* Get and register a snapshot */
-       snapshot = GetSnapshotData(snapshot);
-       snapshot = RegisterSnapshotOnOwner(snapshot, TopTransactionResourceOwner);
+       /* Get the snapshot, or check that it's safe to use */
+       if (!TransactionIdIsValid(sourcexid))
+               snapshot = GetSnapshotData(snapshot);
+       else if (!ProcArrayInstallImportedXmin(snapshot->xmin, sourcexid))
+       {
+               ReleasePredXact(sxact);
+               LWLockRelease(SerializableXactHashLock);
+               ereport(ERROR,
+                               (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                                errmsg("could not import the requested snapshot"),
+                          errdetail("The source transaction %u is not running anymore.",
+                                                sourcexid)));
+       }
 
        /*
         * If there are no serializable transactions which are not read-only, we
@@ -1570,6 +1738,7 @@ RegisterSerializableTransactionInt(Snapshot snapshot)
        /* Initialize the structure. */
        sxact->vxid = vxid;
        sxact->SeqNo.lastCommitBeforeSnapshot = PredXact->LastSxactCommitSeqNo;
+       sxact->prepareSeqNo = InvalidSerCommitSeqNo;
        sxact->commitSeqNo = InvalidSerCommitSeqNo;
        SHMQueueInit(&(sxact->outConflicts));
        SHMQueueInit(&(sxact->inConflicts));
@@ -1595,8 +1764,9 @@ RegisterSerializableTransactionInt(Snapshot snapshot)
                         othersxact != NULL;
                         othersxact = NextPredXact(othersxact))
                {
-                       if (!SxactIsOnFinishedList(othersxact) &&
-                               !SxactIsReadOnly(othersxact))
+                       if (!SxactIsCommitted(othersxact)
+                               && !SxactIsDoomed(othersxact)
+                               && !SxactIsReadOnly(othersxact))
                        {
                                SetPossibleUnsafeConflict(sxact, othersxact);
                        }
@@ -1633,7 +1803,7 @@ RegisterSerializableTransactionInt(Snapshot snapshot)
  * Also store it for easy reference in MySerializableXact.
  */
 void
-RegisterPredicateLockingXid(const TransactionId xid)
+RegisterPredicateLockingXid(TransactionId xid)
 {
        SERIALIZABLEXIDTAG sxidtag;
        SERIALIZABLEXID *sxid;
@@ -1682,7 +1852,7 @@ RegisterPredicateLockingXid(const TransactionId xid)
  * One use is to support proper behavior during GiST index vacuum.
  */
 bool
-PageIsPredicateLocked(const Relation relation, const BlockNumber blkno)
+PageIsPredicateLocked(Relation relation, BlockNumber blkno)
 {
        PREDICATELOCKTARGETTAG targettag;
        uint32          targettaghash;
@@ -1859,7 +2029,7 @@ RestoreScratchTarget(bool lockheld)
 static void
 RemoveTargetIfNoLongerUsed(PREDICATELOCKTARGET *target, uint32 targettaghash)
 {
-       PREDICATELOCKTARGET *rmtarget;
+       PREDICATELOCKTARGET *rmtarget PG_USED_FOR_ASSERTS_ONLY;
 
        Assert(LWLockHeldByMe(SerializablePredicateLockListLock));
 
@@ -1920,7 +2090,7 @@ DeleteChildTargetLocks(const PREDICATELOCKTARGETTAG *newtargettag)
                {
                        uint32          oldtargettaghash;
                        LWLockId        partitionLock;
-                       PREDICATELOCK *rmpredlock;
+                       PREDICATELOCK *rmpredlock PG_USED_FOR_ASSERTS_ONLY;
 
                        oldtargettaghash = PredicateLockTargetTagHashCode(&oldtargettag);
                        partitionLock = PredicateLockHashPartitionLock(oldtargettaghash);
@@ -2073,7 +2243,7 @@ DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag)
        {
                uint32          targettaghash;
                LOCALPREDICATELOCK *parentlock,
-                                  *rmlock;
+                                  *rmlock PG_USED_FOR_ASSERTS_ONLY;
 
                parenttag = nexttag;
                targettaghash = PredicateLockTargetTagHashCode(&parenttag);
@@ -2244,11 +2414,11 @@ PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag)
  * Clear any finer-grained predicate locks this session has on the relation.
  */
 void
-PredicateLockRelation(const Relation relation)
+PredicateLockRelation(Relation relation, Snapshot snapshot)
 {
        PREDICATELOCKTARGETTAG tag;
 
-       if (SkipSerialization(relation))
+       if (!SerializationNeededForRead(relation, snapshot))
                return;
 
        SET_PREDICATELOCKTARGETTAG_RELATION(tag,
@@ -2267,11 +2437,11 @@ PredicateLockRelation(const Relation relation)
  * Clear any finer-grained predicate locks this session has on the relation.
  */
 void
-PredicateLockPage(const Relation relation, const BlockNumber blkno)
+PredicateLockPage(Relation relation, BlockNumber blkno, Snapshot snapshot)
 {
        PREDICATELOCKTARGETTAG tag;
 
-       if (SkipSerialization(relation))
+       if (!SerializationNeededForRead(relation, snapshot))
                return;
 
        SET_PREDICATELOCKTARGETTAG_PAGE(tag,
@@ -2289,13 +2459,13 @@ PredicateLockPage(const Relation relation, const BlockNumber blkno)
  * Skip if this is a temporary table.
  */
 void
-PredicateLockTuple(const Relation relation, const HeapTuple tuple)
+PredicateLockTuple(Relation relation, HeapTuple tuple, Snapshot snapshot)
 {
        PREDICATELOCKTARGETTAG tag;
        ItemPointer tid;
        TransactionId targetxmin;
 
-       if (SkipSerialization(relation))
+       if (!SerializationNeededForRead(relation, snapshot))
                return;
 
        /*
@@ -2322,8 +2492,6 @@ PredicateLockTuple(const Relation relation, const HeapTuple tuple)
                        }
                }
        }
-       else
-               targetxmin = InvalidTransactionId;
 
        /*
         * Do quick-but-not-definitive test for a relation lock first.  This will
@@ -2342,8 +2510,7 @@ PredicateLockTuple(const Relation relation, const HeapTuple tuple)
                                                                         relation->rd_node.dbNode,
                                                                         relation->rd_id,
                                                                         ItemPointerGetBlockNumber(tid),
-                                                                        ItemPointerGetOffsetNumber(tid),
-                                                                        targetxmin);
+                                                                        ItemPointerGetOffsetNumber(tid));
        PredicateLockAcquire(&tag);
 }
 
@@ -2427,8 +2594,8 @@ DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash)
  * Caller must hold SerializablePredicateLockListLock.
  */
 static bool
-TransferPredicateLocksToNewTarget(const PREDICATELOCKTARGETTAG oldtargettag,
-                                                                 const PREDICATELOCKTARGETTAG newtargettag,
+TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag,
+                                                                 PREDICATELOCKTARGETTAG newtargettag,
                                                                  bool removeOld)
 {
        uint32          oldtargettaghash;
@@ -2547,14 +2714,13 @@ TransferPredicateLocksToNewTarget(const PREDICATELOCKTARGETTAG oldtargettag,
                                Assert(found);
                        }
 
-
                        newpredlock = (PREDICATELOCK *)
-                               hash_search_with_hash_value
-                               (PredicateLockHash,
-                                &newpredlocktag,
-                                PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
-                                                                                                                newtargettaghash),
-                                HASH_ENTER_NULL, &found);
+                               hash_search_with_hash_value(PredicateLockHash,
+                                                                                       &newpredlocktag,
+                                        PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
+                                                                                                                  newtargettaghash),
+                                                                                       HASH_ENTER_NULL,
+                                                                                       &found);
                        if (!newpredlock)
                        {
                                /* Out of shared memory. Undo what we've done so far. */
@@ -2644,7 +2810,7 @@ exit:
  * transaction which executed DROP TABLE, the false condition will be useful.
  */
 static void
-DropAllPredicateLocksFromTable(const Relation relation, bool transfer)
+DropAllPredicateLocksFromTable(Relation relation, bool transfer)
 {
        HASH_SEQ_STATUS seqstat;
        PREDICATELOCKTARGET *oldtarget;
@@ -2666,7 +2832,7 @@ DropAllPredicateLocksFromTable(const Relation relation, bool transfer)
        if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
                return;
 
-       if (SkipPredicateLocksForRelation(relation))
+       if (!PredicateLockingNeededForRelation(relation))
                return;
 
        dbId = relation->rd_node.dbNode;
@@ -2790,12 +2956,12 @@ DropAllPredicateLocksFromTable(const Relation relation, bool transfer)
                                newpredlocktag.myTarget = heaptarget;
                                newpredlocktag.myXact = oldXact;
                                newpredlock = (PREDICATELOCK *)
-                                       hash_search_with_hash_value
-                                       (PredicateLockHash,
-                                        &newpredlocktag,
+                                       hash_search_with_hash_value(PredicateLockHash,
+                                                                                               &newpredlocktag,
                                         PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
                                                                                                                  heaptargettaghash),
-                                        HASH_ENTER, &found);
+                                                                                               HASH_ENTER,
+                                                                                               &found);
                                if (!found)
                                {
                                        SHMQueueInsertBefore(&(heaptarget->predicateLocks),
@@ -2840,7 +3006,7 @@ DropAllPredicateLocksFromTable(const Relation relation, bool transfer)
  *             relation to a single relation lock on the heap.
  */
 void
-TransferPredicateLocksToHeapRelation(const Relation relation)
+TransferPredicateLocksToHeapRelation(Relation relation)
 {
        DropAllPredicateLocksFromTable(relation, true);
 }
@@ -2861,8 +3027,8 @@ TransferPredicateLocksToHeapRelation(const Relation relation)
  * which hold the locks getting in and noticing.
  */
 void
-PredicateLockPageSplit(const Relation relation, const BlockNumber oldblkno,
-                                          const BlockNumber newblkno)
+PredicateLockPageSplit(Relation relation, BlockNumber oldblkno,
+                                          BlockNumber newblkno)
 {
        PREDICATELOCKTARGETTAG oldtargettag;
        PREDICATELOCKTARGETTAG newtargettag;
@@ -2881,7 +3047,7 @@ PredicateLockPageSplit(const Relation relation, const BlockNumber oldblkno,
        if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
                return;
 
-       if (SkipPredicateLocksForRelation(relation))
+       if (!PredicateLockingNeededForRelation(relation))
                return;
 
        Assert(oldblkno != newblkno);
@@ -2946,8 +3112,8 @@ PredicateLockPageSplit(const Relation relation, const BlockNumber oldblkno,
  * occurs in the context of another transaction isolation level.
  */
 void
-PredicateLockPageCombine(const Relation relation, const BlockNumber oldblkno,
-                                                const BlockNumber newblkno)
+PredicateLockPageCombine(Relation relation, BlockNumber oldblkno,
+                                                BlockNumber newblkno)
 {
        /*
         * Page combines differ from page splits in that we ought to be able to
@@ -3018,7 +3184,7 @@ SetNewSxactGlobalXmin(void)
  * holding locks.
  */
 void
-ReleasePredicateLocks(const bool isCommit)
+ReleasePredicateLocks(bool isCommit)
 {
        bool            needToClear;
        RWConflict      conflict,
@@ -3044,8 +3210,9 @@ ReleasePredicateLocks(const bool isCommit)
        }
 
        Assert(!isCommit || SxactIsPrepared(MySerializableXact));
-       Assert(!SxactIsRolledBack(MySerializableXact));
+       Assert(!isCommit || !SxactIsDoomed(MySerializableXact));
        Assert(!SxactIsCommitted(MySerializableXact));
+       Assert(!SxactIsRolledBack(MySerializableXact));
 
        /* may not be serializable during COMMIT/ROLLBACK PREPARED */
        if (MySerializableXact->pid != 0)
@@ -3085,7 +3252,28 @@ ReleasePredicateLocks(const bool isCommit)
        }
        else
        {
+               /*
+                * The DOOMED flag indicates that we intend to roll back this
+                * transaction and so it should not cause serialization failures for
+                * other transactions that conflict with it. Note that this flag might
+                * already be set, if another backend marked this transaction for
+                * abort.
+                *
+                * The ROLLED_BACK flag further indicates that ReleasePredicateLocks
+                * has been called, and so the SerializableXact is eligible for
+                * cleanup. This means it should not be considered when calculating
+                * SxactGlobalXmin.
+                */
+               MySerializableXact->flags |= SXACT_FLAG_DOOMED;
                MySerializableXact->flags |= SXACT_FLAG_ROLLED_BACK;
+
+               /*
+                * If the transaction was previously prepared, but is now failing due
+                * to a ROLLBACK PREPARED or (hopefully very rare) error after the
+                * prepare, clear the prepared flag.  This simplifies conflict
+                * checking.
+                */
+               MySerializableXact->flags &= ~SXACT_FLAG_PREPARED;
        }
 
        if (!topLevelIsDeclaredReadOnly)
@@ -3167,8 +3355,8 @@ ReleasePredicateLocks(const bool isCommit)
                        && SxactIsCommitted(conflict->sxactIn))
                {
                        if ((MySerializableXact->flags & SXACT_FLAG_CONFLICT_OUT) == 0
-                               || conflict->sxactIn->commitSeqNo < MySerializableXact->SeqNo.earliestOutConflictCommit)
-                               MySerializableXact->SeqNo.earliestOutConflictCommit = conflict->sxactIn->commitSeqNo;
+                               || conflict->sxactIn->prepareSeqNo < MySerializableXact->SeqNo.earliestOutConflictCommit)
+                               MySerializableXact->SeqNo.earliestOutConflictCommit = conflict->sxactIn->prepareSeqNo;
                        MySerializableXact->flags |= SXACT_FLAG_CONFLICT_OUT;
                }
 
@@ -3310,30 +3498,6 @@ ReleasePredicateLocks(const bool isCommit)
        }
 }
 
-/*
- * ReleasePredicateLocksIfROSafe
- *             Check if the current transaction is read only and operating on
- *             a safe snapshot. If so, release predicate locks and return
- *             true.
- *
- * A transaction is flagged as RO_SAFE if all concurrent R/W
- * transactions commit without having conflicts out to an earlier
- * snapshot, thus ensuring that no conflicts are possible for this
- * transaction. Thus, we call this function as part of the
- * SkipSerialization check on all public interface methods.
- */
-static bool
-ReleasePredicateLocksIfROSafe(void)
-{
-       if (SxactIsROSafe(MySerializableXact))
-       {
-               ReleasePredicateLocks(false);
-               return true;
-       }
-       else
-               return false;
-}
-
 /*
  * Clear old predicate locks, belonging to committed transactions that are no
  * longer interesting to any in-progress transaction.
@@ -3378,10 +3542,29 @@ ClearOldPredicateLocks(void)
                else if (finishedSxact->commitSeqNo > PredXact->HavePartialClearedThrough
                   && finishedSxact->commitSeqNo <= PredXact->CanPartialClearThrough)
                {
+                       /*
+                        * Any active transactions that took their snapshot before this
+                        * transaction committed are read-only, so we can clear part of
+                        * its state.
+                        */
                        LWLockRelease(SerializableXactHashLock);
-                       ReleaseOneSerializableXact(finishedSxact,
-                                                                          !SxactIsReadOnly(finishedSxact),
-                                                                          false);
+
+                       if (SxactIsReadOnly(finishedSxact))
+                       {
+                               /* A read-only transaction can be removed entirely */
+                               SHMQueueDelete(&(finishedSxact->finishedLink));
+                               ReleaseOneSerializableXact(finishedSxact, false, false);
+                       }
+                       else
+                       {
+                               /*
+                                * A read-write transaction can only be partially cleared. We
+                                * need to keep the SERIALIZABLEXACT but can release the
+                                * SIREAD locks and conflicts in.
+                                */
+                               ReleaseOneSerializableXact(finishedSxact, true, false);
+                       }
+
                        PredXact->HavePartialClearedThrough = finishedSxact->commitSeqNo;
                        LWLockAcquire(SerializableXactHashLock, LW_SHARED);
                }
@@ -3487,6 +3670,7 @@ ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
 
        Assert(sxact != NULL);
        Assert(SxactIsRolledBack(sxact) || SxactIsCommitted(sxact));
+       Assert(partial || !SxactIsOnFinishedList(sxact));
        Assert(LWLockHeldByMe(SerializableFinishedListLock));
 
        /*
@@ -3678,8 +3862,9 @@ XidIsConcurrent(TransactionId xid)
  * currently no known reason to call this function from an index AM.
  */
 void
-CheckForSerializableConflictOut(const bool visible, const Relation relation,
-                                                               const HeapTuple tuple, const Buffer buffer)
+CheckForSerializableConflictOut(bool visible, Relation relation,
+                                                               HeapTuple tuple, Buffer buffer,
+                                                               Snapshot snapshot)
 {
        TransactionId xid;
        SERIALIZABLEXIDTAG sxidtag;
@@ -3687,15 +3872,16 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
        SERIALIZABLEXACT *sxact;
        HTSV_Result htsvResult;
 
-       if (SkipSerialization(relation))
+       if (!SerializationNeededForRead(relation, snapshot))
                return;
 
-       if (SxactIsMarkedForDeath(MySerializableXact))
+       /* Check if someone else has already decided that we need to die */
+       if (SxactIsDoomed(MySerializableXact))
        {
                ereport(ERROR,
                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                errdetail("Cancelled on identification as a pivot, during conflict out checking."),
+                                errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
                                 errhint("The transaction might succeed if retried.")));
        }
 
@@ -3706,7 +3892,7 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
         * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
         * is going on with it.
         */
-       htsvResult = HeapTupleSatisfiesVacuum(tuple->t_data, TransactionXmin, buffer);
+       htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
        switch (htsvResult)
        {
                case HEAPTUPLE_LIVE:
@@ -3717,10 +3903,10 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
                case HEAPTUPLE_RECENTLY_DEAD:
                        if (!visible)
                                return;
-                       xid = HeapTupleHeaderGetXmax(tuple->t_data);
+                       xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                        break;
                case HEAPTUPLE_DELETE_IN_PROGRESS:
-                       xid = HeapTupleHeaderGetXmax(tuple->t_data);
+                       xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                        break;
                case HEAPTUPLE_INSERT_IN_PROGRESS:
                        xid = HeapTupleHeaderGetXmin(tuple->t_data);
@@ -3784,7 +3970,7 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
                                ereport(ERROR,
                                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                               errdetail("Cancelled on conflict out to old pivot %u.", xid),
+                                                errdetail_internal("Reason code: Canceled on conflict out to old pivot %u.", xid),
                                          errhint("The transaction might succeed if retried.")));
 
                        if (SxactHasSummaryConflictIn(MySerializableXact)
@@ -3792,7 +3978,7 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
                                ereport(ERROR,
                                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                                errdetail("Cancelled on identification as a pivot, with conflict out to old committed transaction %u.", xid),
+                                                errdetail_internal("Reason code: Canceled on identification as a pivot, with conflict out to old committed transaction %u.", xid),
                                          errhint("The transaction might succeed if retried.")));
 
                        MySerializableXact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
@@ -3804,11 +3990,9 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
        }
        sxact = sxid->myXact;
        Assert(TransactionIdEquals(sxact->topXid, xid));
-       if (sxact == MySerializableXact
-               || SxactIsRolledBack(sxact)
-               || SxactIsMarkedForDeath(sxact))
+       if (sxact == MySerializableXact || SxactIsDoomed(sxact))
        {
-               /* We can't conflict with our own transaction or one rolled back. */
+               /* Can't conflict with ourself or a transaction that will roll back. */
                LWLockRelease(SerializableXactHashLock);
                return;
        }
@@ -3817,13 +4001,13 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
         * We have a conflict out to a transaction which has a conflict out to a
         * summarized transaction.      That summarized transaction must have
         * committed first, and we can't tell when it committed in relation to our
-        * snapshot acquisition, so something needs to be cancelled.
+        * snapshot acquisition, so something needs to be canceled.
         */
        if (SxactHasSummaryConflictOut(sxact))
        {
                if (!SxactIsPrepared(sxact))
                {
-                       sxact->flags |= SXACT_FLAG_MARKED_FOR_DEATH;
+                       sxact->flags |= SXACT_FLAG_DOOMED;
                        LWLockRelease(SerializableXactHashLock);
                        return;
                }
@@ -3833,7 +4017,7 @@ CheckForSerializableConflictOut(const bool visible, const Relation relation,
                        ereport(ERROR,
                                        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                         errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                        errdetail("Cancelled on conflict out to old pivot."),
+                                        errdetail_internal("Reason code: Canceled on conflict out to old pivot."),
                                         errhint("The transaction might succeed if retried.")));
                }
        }
@@ -3950,7 +4134,7 @@ CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag)
                                mypredlocktag = predlock->tag;
                        }
                }
-               else if (!SxactIsRolledBack(sxact)
+               else if (!SxactIsDoomed(sxact)
                                 && (!SxactIsCommitted(sxact)
                                         || TransactionIdPrecedes(GetTransactionSnapshot()->xmin,
                                                                                          sxact->finishedBefore))
@@ -3963,7 +4147,7 @@ CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag)
                         * Re-check after getting exclusive lock because the other
                         * transaction may have flagged a conflict.
                         */
-                       if (!SxactIsRolledBack(sxact)
+                       if (!SxactIsDoomed(sxact)
                                && (!SxactIsCommitted(sxact)
                                        || TransactionIdPrecedes(GetTransactionSnapshot()->xmin,
                                                                                         sxact->finishedBefore))
@@ -4059,19 +4243,20 @@ CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag)
  * tuple itself.
  */
 void
-CheckForSerializableConflictIn(const Relation relation, const HeapTuple tuple,
-                                                          const Buffer buffer)
+CheckForSerializableConflictIn(Relation relation, HeapTuple tuple,
+                                                          Buffer buffer)
 {
        PREDICATELOCKTARGETTAG targettag;
 
-       if (SkipSerialization(relation))
+       if (!SerializationNeededForWrite(relation))
                return;
 
-       if (SxactIsMarkedForDeath(MySerializableXact))
+       /* Check if someone else has already decided that we need to die */
+       if (SxactIsDoomed(MySerializableXact))
                ereport(ERROR,
                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                errdetail("Cancelled on identification as a pivot, during conflict in checking."),
+                                errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict in checking."),
                                 errhint("The transaction might succeed if retried.")));
 
        /*
@@ -4094,9 +4279,8 @@ CheckForSerializableConflictIn(const Relation relation, const HeapTuple tuple,
                SET_PREDICATELOCKTARGETTAG_TUPLE(targettag,
                                                                                 relation->rd_node.dbNode,
                                                                                 relation->rd_id,
-                                                ItemPointerGetBlockNumber(&(tuple->t_data->t_ctid)),
-                                               ItemPointerGetOffsetNumber(&(tuple->t_data->t_ctid)),
-                                                                         HeapTupleHeaderGetXmin(tuple->t_data));
+                                                                 ItemPointerGetBlockNumber(&(tuple->t_self)),
+                                                               ItemPointerGetOffsetNumber(&(tuple->t_self)));
                CheckTargetForConflictsIn(&targettag);
        }
 
@@ -4143,7 +4327,7 @@ CheckForSerializableConflictIn(const Relation relation, const HeapTuple tuple,
  * lead to some false positives, but it doesn't seem worth the trouble.)
  */
 void
-CheckTableForSerializableConflictIn(const Relation relation)
+CheckTableForSerializableConflictIn(Relation relation)
 {
        HASH_SEQ_STATUS seqstat;
        PREDICATELOCKTARGET *target;
@@ -4160,7 +4344,7 @@ CheckTableForSerializableConflictIn(const Relation relation)
        if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
                return;
 
-       if (SkipSerialization(relation))
+       if (!SerializationNeededForWrite(relation))
                return;
 
        /*
@@ -4307,6 +4491,11 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
         * - the writer committed before T2
         * - the reader is a READ ONLY transaction and the reader was concurrent
         *       with T2 (= reader acquired its snapshot before T2 committed)
+        *
+        * We also handle the case that T2 is prepared but not yet committed
+        * here. In that case T2 has already checked for conflicts, so if it
+        * commits first, making the above conflict real, it's too late for it
+        * to abort.
         *------------------------------------------------------------------------
         */
        if (!failure)
@@ -4325,13 +4514,13 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
                {
                        SERIALIZABLEXACT *t2 = conflict->sxactIn;
 
-                       if (SxactIsCommitted(t2)
+                       if (SxactIsPrepared(t2)
                                && (!SxactIsCommitted(reader)
-                                       || t2->commitSeqNo <= reader->commitSeqNo)
+                                       || t2->prepareSeqNo <= reader->commitSeqNo)
                                && (!SxactIsCommitted(writer)
-                                       || t2->commitSeqNo <= writer->commitSeqNo)
+                                       || t2->prepareSeqNo <= writer->commitSeqNo)
                                && (!SxactIsReadOnly(reader)
-                          || t2->commitSeqNo <= reader->SeqNo.lastCommitBeforeSnapshot))
+                         || t2->prepareSeqNo <= reader->SeqNo.lastCommitBeforeSnapshot))
                        {
                                failure = true;
                                break;
@@ -4344,7 +4533,8 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
        }
 
        /*------------------------------------------------------------------------
-        * Check whether the reader has become a pivot with a committed writer:
+        * Check whether the reader has become a pivot with a writer
+        * that's committed (or prepared):
         *
         *              T0 ------> R ------> W
         *                       rw                rw
@@ -4355,7 +4545,7 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
         * - T0 is READ ONLY, and overlaps the writer
         *------------------------------------------------------------------------
         */
-       if (!failure && SxactIsCommitted(writer) && !SxactIsReadOnly(reader))
+       if (!failure && SxactIsPrepared(writer) && !SxactIsReadOnly(reader))
        {
                if (SxactHasSummaryConflictIn(reader))
                {
@@ -4371,11 +4561,11 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
                {
                        SERIALIZABLEXACT *t0 = conflict->sxactOut;
 
-                       if (!SxactIsRolledBack(t0)
+                       if (!SxactIsDoomed(t0)
                                && (!SxactIsCommitted(t0)
-                                       || t0->commitSeqNo >= writer->commitSeqNo)
+                                       || t0->commitSeqNo >= writer->prepareSeqNo)
                                && (!SxactIsReadOnly(t0)
-                          || t0->SeqNo.lastCommitBeforeSnapshot >= writer->commitSeqNo))
+                         || t0->SeqNo.lastCommitBeforeSnapshot >= writer->prepareSeqNo))
                        {
                                failure = true;
                                break;
@@ -4403,7 +4593,7 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
                        ereport(ERROR,
                                        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                         errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                        errdetail("Cancelled on identification as a pivot, during write."),
+                                        errdetail_internal("Reason code: Canceled on identification as a pivot, during write."),
                                         errhint("The transaction might succeed if retried.")));
                }
                else if (SxactIsPrepared(writer))
@@ -4415,10 +4605,10 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
                        ereport(ERROR,
                                        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                         errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                        errdetail("Cancelled on conflict out to pivot %u, during read.", writer->topXid),
+                                        errdetail_internal("Reason code: Canceled on conflict out to pivot %u, during read.", writer->topXid),
                                         errhint("The transaction might succeed if retried.")));
                }
-               writer->flags |= SXACT_FLAG_MARKED_FOR_DEATH;
+               writer->flags |= SXACT_FLAG_DOOMED;
        }
 }
 
@@ -4436,7 +4626,7 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
  * marked for death, because rolling back another transaction might mean
  * that we flail without ever making progress. This transaction is
  * committing writes, so letting it commit ensures progress.  If we
- * cancelled the far conflict, it might immediately fail again on retry.
+ * canceled the far conflict, it might immediately fail again on retry.
  */
 void
 PreCommit_CheckForSerializationFailure(void)
@@ -4450,13 +4640,14 @@ PreCommit_CheckForSerializationFailure(void)
 
        LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
 
-       if (SxactIsMarkedForDeath(MySerializableXact))
+       /* Check if someone else has already decided that we need to die */
+       if (SxactIsDoomed(MySerializableXact))
        {
                LWLockRelease(SerializableXactHashLock);
                ereport(ERROR,
                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                errdetail("Cancelled on identification as a pivot, during commit attempt."),
+                                errdetail_internal("Reason code: Canceled on identification as a pivot, during commit attempt."),
                                 errhint("The transaction might succeed if retried.")));
        }
 
@@ -4467,8 +4658,7 @@ PreCommit_CheckForSerializationFailure(void)
        while (nearConflict)
        {
                if (!SxactIsCommitted(nearConflict->sxactOut)
-                       && !SxactIsRolledBack(nearConflict->sxactOut)
-                       && !SxactIsMarkedForDeath(nearConflict->sxactOut))
+                       && !SxactIsDoomed(nearConflict->sxactOut))
                {
                        RWConflict      farConflict;
 
@@ -4481,10 +4671,24 @@ PreCommit_CheckForSerializationFailure(void)
                                if (farConflict->sxactOut == MySerializableXact
                                        || (!SxactIsCommitted(farConflict->sxactOut)
                                                && !SxactIsReadOnly(farConflict->sxactOut)
-                                               && !SxactIsRolledBack(farConflict->sxactOut)
-                                               && !SxactIsMarkedForDeath(farConflict->sxactOut)))
+                                               && !SxactIsDoomed(farConflict->sxactOut)))
                                {
-                                       nearConflict->sxactOut->flags |= SXACT_FLAG_MARKED_FOR_DEATH;
+                                       /*
+                                        * Normally, we kill the pivot transaction to make sure we
+                                        * make progress if the failing transaction is retried.
+                                        * However, we can't kill it if it's already prepared, so
+                                        * in that case we commit suicide instead.
+                                        */
+                                       if (SxactIsPrepared(nearConflict->sxactOut))
+                                       {
+                                               LWLockRelease(SerializableXactHashLock);
+                                               ereport(ERROR,
+                                                               (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
+                                                                errmsg("could not serialize access due to read/write dependencies among transactions"),
+                                                                errdetail_internal("Reason code: Canceled on commit attempt with conflict in from prepared pivot."),
+                                                                errhint("The transaction might succeed if retried.")));
+                                       }
+                                       nearConflict->sxactOut->flags |= SXACT_FLAG_DOOMED;
                                        break;
                                }
                                farConflict = (RWConflict)
@@ -4500,6 +4704,7 @@ PreCommit_CheckForSerializationFailure(void)
                                                 offsetof(RWConflictData, inLink));
        }
 
+       MySerializableXact->prepareSeqNo = ++(PredXact->LastSxactCommitSeqNo);
        MySerializableXact->flags |= SXACT_FLAG_PREPARED;
 
        LWLockRelease(SerializableXactHashLock);
@@ -4538,14 +4743,11 @@ AtPrepare_PredicateLocks(void)
        xactRecord->flags = MySerializableXact->flags;
 
        /*
-        * Tweak the flags. Since we're not going to output the inConflicts and
-        * outConflicts lists, if they're non-empty we'll represent that by
-        * setting the appropriate summary conflict flags.
+        * Note that we don't include the list of conflicts in our out in the
+        * statefile, because new conflicts can be added even after the
+        * transaction prepares. We'll just make a conservative assumption during
+        * recovery instead.
         */
-       if (!SHMQueueEmpty(&MySerializableXact->inConflicts))
-               xactRecord->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
-       if (!SHMQueueEmpty(&MySerializableXact->outConflicts))
-               xactRecord->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
 
        RegisterTwoPhaseRecord(TWOPHASE_RM_PREDICATELOCK_ID, 0,
                                                   &record, sizeof(record));
@@ -4674,20 +4876,12 @@ predicatelock_twophase_recover(TransactionId xid, uint16 info,
                sxact->pid = 0;
 
                /* a prepared xact hasn't committed yet */
+               sxact->prepareSeqNo = RecoverySerCommitSeqNo;
                sxact->commitSeqNo = InvalidSerCommitSeqNo;
                sxact->finishedBefore = InvalidTransactionId;
 
                sxact->SeqNo.lastCommitBeforeSnapshot = RecoverySerCommitSeqNo;
 
-
-               /*
-                * We don't need the details of a prepared transaction's conflicts,
-                * just whether it had conflicts in or out (which we get from the
-                * flags)
-                */
-               SHMQueueInit(&(sxact->outConflicts));
-               SHMQueueInit(&(sxact->inConflicts));
-
                /*
                 * Don't need to track this; no transactions running at the time the
                 * recovered xact started are still active, except possibly other
@@ -4709,6 +4903,16 @@ predicatelock_twophase_recover(TransactionId xid, uint16 info,
                                   (MaxBackends + max_prepared_xacts));
                }
 
+               /*
+                * We don't know whether the transaction had any conflicts or not, so
+                * we'll conservatively assume that it had both a conflict in and a
+                * conflict out, and represent that with the summary conflict flags.
+                */
+               SHMQueueInit(&(sxact->outConflicts));
+               SHMQueueInit(&(sxact->inConflicts));
+               sxact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
+               sxact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
+
                /* Register the transaction's xid */
                sxidtag.xid = xid;
                sxid = (SERIALIZABLEXID *) hash_search(SerializableXidHash,