]> granicus.if.org Git - postgresql/blobdiff - src/backend/storage/lmgr/predicate.c
Update copyright for 2014
[postgresql] / src / backend / storage / lmgr / predicate.c
index f0c8ee48c340403fdf075b8ee55b44066971845e..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, Snapshot snapshot)
  *             PredicateLockPage(Relation relation, BlockNumber blkno,
  *             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)
  *
 
 #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"
@@ -305,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)
 
@@ -371,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;
 
@@ -411,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);
@@ -449,13 +460,14 @@ static void OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *read
 
 /*
  * Does this relation participate in predicate locking? Temporary and system
- * relations are exempt.
+ * relations are exempt, as are materialized views.
  */
 static inline bool
 PredicateLockingNeededForRelation(Relation relation)
 {
        return !(relation->rd_id < FirstBootstrapObjectId ||
-                        RelationUsesLocalBuffers(relation));
+                        RelationUsesLocalBuffers(relation) ||
+                        relation->rd_rel->relkind == RELKIND_MATVIEW);
 }
 
 /*
@@ -656,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);
@@ -684,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);
@@ -761,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;
 }
@@ -1184,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);
@@ -1224,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;
@@ -1478,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)
@@ -1489,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 */
@@ -1528,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);
        }
 
        /*
@@ -1542,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;
@@ -1583,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();
@@ -1600,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
@@ -1644,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));
@@ -1669,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);
                        }
@@ -1933,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));
 
@@ -1994,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);
@@ -2147,7 +2243,7 @@ DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag)
        {
                uint32          targettaghash;
                LOCALPREDICATELOCK *parentlock,
-                                  *rmlock;
+                                  *rmlock PG_USED_FOR_ASSERTS_ONLY;
 
                parenttag = nexttag;
                targettaghash = PredicateLockTargetTagHashCode(&parenttag);
@@ -2396,8 +2492,6 @@ PredicateLockTuple(Relation relation, HeapTuple tuple, Snapshot snapshot)
                        }
                }
        }
-       else
-               targetxmin = InvalidTransactionId;
 
        /*
         * Do quick-but-not-definitive test for a relation lock first.  This will
@@ -2416,8 +2510,7 @@ PredicateLockTuple(Relation relation, HeapTuple tuple, Snapshot snapshot)
                                                                         relation->rd_node.dbNode,
                                                                         relation->rd_id,
                                                                         ItemPointerGetBlockNumber(tid),
-                                                                        ItemPointerGetOffsetNumber(tid),
-                                                                        targetxmin);
+                                                                        ItemPointerGetOffsetNumber(tid));
        PredicateLockAcquire(&tag);
 }
 
@@ -2624,8 +2717,8 @@ TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag,
                        newpredlock = (PREDICATELOCK *)
                                hash_search_with_hash_value(PredicateLockHash,
                                                                                        &newpredlocktag,
-                                                                                       PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
-                                                                                                                                                                       newtargettaghash),
+                                        PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
+                                                                                                                  newtargettaghash),
                                                                                        HASH_ENTER_NULL,
                                                                                        &found);
                        if (!newpredlock)
@@ -2865,8 +2958,8 @@ DropAllPredicateLocksFromTable(Relation relation, bool transfer)
                                newpredlock = (PREDICATELOCK *)
                                        hash_search_with_hash_value(PredicateLockHash,
                                                                                                &newpredlocktag,
-                                                                                               PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
-                                                                                                                                                                               heaptargettaghash),
+                                        PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
+                                                                                                                 heaptargettaghash),
                                                                                                HASH_ENTER,
                                                                                                &found);
                                if (!found)
@@ -3173,6 +3266,7 @@ ReleasePredicateLocks(bool isCommit)
                 */
                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
@@ -3261,8 +3355,8 @@ ReleasePredicateLocks(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;
                }
 
@@ -3448,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);
                }
@@ -3557,6 +3670,7 @@ ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
 
        Assert(sxact != NULL);
        Assert(SxactIsRolledBack(sxact) || SxactIsCommitted(sxact));
+       Assert(partial || !SxactIsOnFinishedList(sxact));
        Assert(LWLockHeldByMe(SerializableFinishedListLock));
 
        /*
@@ -3767,7 +3881,7 @@ CheckForSerializableConflictOut(bool visible, Relation relation,
                ereport(ERROR,
                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                errdetail("Canceled 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.")));
        }
 
@@ -3778,7 +3892,7 @@ CheckForSerializableConflictOut(bool visible, 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:
@@ -3789,10 +3903,10 @@ CheckForSerializableConflictOut(bool visible, 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);
@@ -3856,7 +3970,7 @@ CheckForSerializableConflictOut(bool visible, Relation relation,
                                ereport(ERROR,
                                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                               errdetail("Canceled 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)
@@ -3864,7 +3978,7 @@ CheckForSerializableConflictOut(bool visible, Relation relation,
                                ereport(ERROR,
                                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                                errdetail("Canceled 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;
@@ -3903,7 +4017,7 @@ CheckForSerializableConflictOut(bool visible, Relation relation,
                        ereport(ERROR,
                                        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                         errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                        errdetail("Canceled on conflict out to old pivot."),
+                                        errdetail_internal("Reason code: Canceled on conflict out to old pivot."),
                                         errhint("The transaction might succeed if retried.")));
                }
        }
@@ -4142,7 +4256,7 @@ CheckForSerializableConflictIn(Relation relation, HeapTuple tuple,
                ereport(ERROR,
                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                errdetail("Canceled 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.")));
 
        /*
@@ -4165,9 +4279,8 @@ CheckForSerializableConflictIn(Relation relation, 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);
        }
 
@@ -4401,18 +4514,13 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
                {
                        SERIALIZABLEXACT *t2 = conflict->sxactIn;
 
-                       /*
-                        * Note that if T2 is merely prepared but not yet committed, we
-                        * rely on t->commitSeqNo being InvalidSerCommitSeqNo, which is
-                        * larger than any valid commit sequence number.
-                        */
                        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;
@@ -4453,17 +4561,11 @@ OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
                {
                        SERIALIZABLEXACT *t0 = conflict->sxactOut;
 
-                       /*
-                        * Note that if the writer is merely prepared but not yet
-                        * committed, we rely on writer->commitSeqNo being
-                        * InvalidSerCommitSeqNo, which is larger than any valid commit
-                        * sequence number.
-                        */
                        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;
@@ -4491,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("Canceled 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))
@@ -4503,7 +4605,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("Canceled 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_DOOMED;
@@ -4545,7 +4647,7 @@ PreCommit_CheckForSerializationFailure(void)
                ereport(ERROR,
                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                errdetail("Canceled 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.")));
        }
 
@@ -4583,7 +4685,7 @@ PreCommit_CheckForSerializationFailure(void)
                                                ereport(ERROR,
                                                                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                                                 errmsg("could not serialize access due to read/write dependencies among transactions"),
-                                                                errdetail("Canceled on commit attempt with conflict in from prepared pivot."),
+                                                                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;
@@ -4602,6 +4704,7 @@ PreCommit_CheckForSerializationFailure(void)
                                                 offsetof(RWConflictData, inLink));
        }
 
+       MySerializableXact->prepareSeqNo = ++(PredXact->LastSxactCommitSeqNo);
        MySerializableXact->flags |= SXACT_FLAG_PREPARED;
 
        LWLockRelease(SerializableXactHashLock);
@@ -4640,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));
@@ -4776,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
@@ -4811,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,