From 3bd004c4aff474b07c8d0a56342d9139bb1ea7c2 Mon Sep 17 00:00:00 2001 From: Matthias van de Meent Date: Fri, 9 Oct 2026 23:06:04 +0200 Subject: [PATCH v3 3/3] procarray: Implement full lockless snapshot reuse In the previous commit, we'd only reuse a snapshot if we had an xmin installed. Now, we also install the reused snapshot's xmin without holding a lock if we determine no transaction has committed since we gathered this snapshot's data. This means we'll reuse all snapshot data whenever there was no recent commit, all without taking any locks in any lock mode. --- src/backend/storage/ipc/procarray.c | 143 ++++++++++++++-------------- src/include/access/varsup.h | 17 ++++ 2 files changed, 89 insertions(+), 71 deletions(-) diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c index ffd584bffdb..b2140673d71 100644 --- a/src/backend/storage/ipc/procarray.c +++ b/src/backend/storage/ipc/procarray.c @@ -2022,56 +2022,17 @@ GetMaxSnapshotSubxidCount(void) return TOTAL_MAX_CACHED_SUBXIDS; } -static inline bool -GetSnapshotDataReuseUnlocked(Snapshot snapshot, bool *try_reuse) -{ - uint64 curXactCompletionCount; - - if (!TransactionIdIsValid(MyProc->xmin)) - { - *try_reuse = true; - return false; - } - - if (unlikely(snapshot->snapXactCompletionCount == 0)) - { - *try_reuse = false; - return false; - } - - curXactCompletionCount = - pg_atomic_read_u64(&TransamVariables->xactCompletionCount); - - if (curXactCompletionCount != snapshot->snapXactCompletionCount) - { - *try_reuse = false; - return false; - } - - RecentXmin = snapshot->xmin; - Assert(TransactionIdPrecedesOrEquals(TransactionXmin, RecentXmin)); - snapshot->curcid = GetCurrentCommandId(false); - snapshot->active_count = 0; - snapshot->regd_count = 0; - snapshot->copied = false; - - return true; -} /* * Helper function for GetSnapshotData() that checks if the bulk of the * visibility information in the snapshot is still valid. If so, it updates * the fields that need to change and returns true. Otherwise it returns * false. - * - * This very likely can be evolved to not need ProcArrayLock held (at very - * least in the case we already hold a snapshot), but that's for another day. */ static bool GetSnapshotDataReuse(Snapshot snapshot) { - uint64 curXactCompletionCount; - - Assert(LWLockHeldByMe(ProcArrayLock)); + uint64 curXactCompletionCount; + TransactionId prevProcXmin; if (unlikely(snapshot->snapXactCompletionCount == 0)) return false; @@ -2082,28 +2043,70 @@ GetSnapshotDataReuse(Snapshot snapshot) if (curXactCompletionCount != snapshot->snapXactCompletionCount) return false; - /* - * If the current xactCompletionCount is still the same as it was at the - * time the snapshot was built, we can be sure that rebuilding the - * contents of the snapshot the hard way would result in the same snapshot - * contents: - * - * As explained in transam/README, the set of xids considered running by - * GetSnapshotData() cannot change while ProcArrayLock is held. Snapshot - * contents only depend on transactions with xids and xactCompletionCount - * is incremented whenever a transaction with an xid finishes (while - * holding ProcArrayLock exclusively). Thus the xactCompletionCount check - * ensures we would detect if the snapshot would have changed. - * - * As the snapshot contents are the same as it was before, it is safe to - * re-enter the snapshot's xmin into the PGPROC array. None of the rows - * visible under the snapshot could already have been removed (that'd - * require the set of running transactions to change) and it fulfills the - * requirement that concurrent GetSnapshotData() calls yield the same - * xmin. - */ - if (!TransactionIdIsValid(MyProc->xmin)) - MyProc->xmin = TransactionXmin = snapshot->xmin; + prevProcXmin = MyProc->xmin; + + if (!TransactionIdIsValid(prevProcXmin)) + { + /* + * If the current xactCompletionCount is still the same as it was at the + * time the snapshot was built, we can be sure that rebuilding the + * contents of the snapshot the hard way would result in the same snapshot + * contents: + * + * As explained in transam/README, the set of xids considered running by + * GetSnapshotData() cannot change while ProcArrayLock is held. Snapshot + * contents only depend on transactions with xids and xactCompletionCount + * is incremented whenever a transaction with an xid finishes (while + * holding ProcArrayLock exclusively). Thus the xactCompletionCount check + * ensures we would detect if the snapshot would have changed. + * + * As the snapshot contents are the same as it was before, it is safe to + * re-enter the snapshot's xmin into the PGPROC array. None of the rows + * visible under the snapshot could already have been removed (that'd + * require the set of running transactions to change) and it fulfills the + * requirement that concurrent GetSnapshotData() calls yield the same + * xmin. + * + * However, we must make sure that a concurrent commit doesn't happen + * while we're installing our xmin, so we have to make sure the + * completion count doesn't change under our feet, or roll back our + * changes and stop reusing this snapshot. + * + * We *must* do the validation check, because the data contained in the + * reused snapshot could be cleaned up with a visibility horizon + * constructed between the completion count test and us publishing the + * reused snapshot's xmin. + * + * It is safe to install and later remove the xmin: visibility horizons + * are only approximate, and are known to move backwards in some cases. + */ + MyProc->xmin = snapshot->xmin; + /* + * Barrier is used here to make sure our xmin is installed before we + * read the completion count again, so that no concurrent commit has + * invalidated the snapshot. + */ + curXactCompletionCount = pg_atomic_read_membarrier_u64( + &TransamVariables->xactCompletionCount + ); + + if (curXactCompletionCount != snapshot->snapXactCompletionCount) + { + /* + * We published a new xmin, but a transaction completed + * concurrently, so the snapshot's data may now possibly be + * cleaned up. Better roll back our xmin update, and get new + * snapshot data. + */ + MyProc->xmin = prevProcXmin; + + return false; + } + + TransactionXmin = snapshot->xmin; + } + + /* If we reach here, we can reuse the snapshot's data */ RecentXmin = snapshot->xmin; Assert(TransactionIdPrecedesOrEquals(TransactionXmin, RecentXmin)); @@ -2163,7 +2166,6 @@ GetSnapshotData(Snapshot snapshot) int mypgxactoff; TransactionId myxid; uint64 curXactCompletionCount; - bool retry_reuse; TransactionId replication_slot_xmin = InvalidTransactionId; TransactionId replication_slot_catalog_xmin = InvalidTransactionId; @@ -2210,21 +2212,20 @@ GetSnapshotData(Snapshot snapshot) } } - if (GetSnapshotDataReuseUnlocked(snapshot, &retry_reuse)) + /* try to reuse the snapshot data */ + if (GetSnapshotDataReuse(snapshot)) return snapshot; /* * It is sufficient to get shared lock on ProcArrayLock, even if we are * going to set MyProc->xmin. + * + * GetSnapshotDataReuse guarantees that we can't reuse our current + * snapshot data, so we don't need to try that again after taking the + * lock. */ LWLockAcquire(ProcArrayLock, LW_SHARED); - if (retry_reuse && GetSnapshotDataReuse(snapshot)) - { - LWLockRelease(ProcArrayLock); - return snapshot; - } - latest_completed = TransamVariables->latestCompletedXid; mypgxactoff = MyProc->pgxactoff; myxid = other_xids[mypgxactoff]; diff --git a/src/include/access/varsup.h b/src/include/access/varsup.h index 9eec60d1008..f345be11976 100644 --- a/src/include/access/varsup.h +++ b/src/include/access/varsup.h @@ -68,6 +68,9 @@ typedef struct TransamVariablesData * the server. This currently is solely used to check whether * GetSnapshotData() needs to recompute the contents of the snapshot, or * not. There are likely other users of this. Always above 1. + * + * The atomic type is primarily used to avoid torn reads; updates rely + * on ProcArrayLock's barriers for correctness. */ pg_atomic_uint64 xactCompletionCount; @@ -81,11 +84,25 @@ typedef struct TransamVariablesData extern PGDLLIMPORT TransamVariablesData *TransamVariables; +/* + * Increment xact completion count without issuing our own memory barriers. + * We rely on the ProcArrayLock's memory barriers instead. + */ static inline void IncrementXactCompletionCount(void) { uint64 xcc; + /* + * We rely on the memory barrier of the ProcArray unlock to publish + * the xact completion count change; any earlier is still valid but + * not strictly necessary: The value stored in SnapshotData is + * pulled from memory under ProcArrayLock, too. Reuse uses unlocked + * reads for performance in most cases, but needs to use barrier + * reads if it needs to install an xmin to make sure the value didn't + * change by the time we installed that xmin (and so invalidated the + * snapshot we're reusing). + */ Assert(LWLockHeldByMeInMode(ProcArrayLock, LW_EXCLUSIVE)); xcc = pg_atomic_read_u64(&TransamVariables->xactCompletionCount); -- 2.54.0 (Apple Git-157)