[PATCH] Do not reuse recovery snapshots after recovery ends

From: Hannu Krosing <hannuk(at)google(dot)com>
To: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: [PATCH] Do not reuse recovery snapshots after recovery ends
Date: 2026-12-02 18:43:21
Message-ID: CAMT0RQQbXGtGz_zhgZuyrCq7wjDYqQCOPFz-FNTbxgiRYFnGdg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi hackers,

While reviewing a cfbot run for an unrelated patch series, I noticed an
intermittent assertion failure in recovery/061_recovery_target_prefetch on
macOS - Meson [1]:

TRAP: failed Assert("TransactionIdPrecedesOrEquals(TransactionXmin,
RecentXmin)"),
File: "../src/backend/storage/ipc/procarray.c", Line: 2071

This turns out to be a pre-existing race condition in GetSnapshotDataReuse()
during standby promotion, present since commit 623a9ba79bb (PostgreSQL 14).

Root cause
----------

At the end of recovery in StartupXLOG() (src/backend/access/transam/xlog.c):

1. XLogCtl->SharedRecoveryState is set to RECOVERY_STATE_DONE under
XLogCtl->info_lck (while holding ControlFileLock).
2. UpdateControlFile(), WakeupCheckpointer(), and WaitLSNWakeup() run.
3. ShutdownRecoveryTransactionEnvironment() calls
ExpireAllKnownAssignedTransactionIds(), which increments
TransamVariables->xactCompletionCount under ProcArrayLock.

In the window between step 1 and step 3, RecoveryInProgress() already returns
false while TransamVariables->xactCompletionCount has not yet been incremented.

Now suppose an in-progress transaction XID exists in KnownAssignedXids that is
older than latestCompletedXid + 1 (for example, in 061_recovery_target_prefetch
recovery stops mid-transaction during CREATE INDEX):

1. Before promotion (at xactCompletionCount = K), a backend builds a static
SnapshotData (e.g., CatalogSnapshotData) with takenDuringRecovery = true
and xmin = <uncommitted XID from KnownAssignedXids>, while another static
SnapshotData (e.g., CurrentSnapshotData) is still at an older
snapXactCompletionCount (0 or K - 1).
2. During the promotion window (after SharedRecoveryState =
RECOVERY_STATE_DONE,
before ExpireAllKnownAssignedTransactionIds()), the backend starts a
transaction and calls GetSnapshotData(&CurrentSnapshotData). Because its
snapXactCompletionCount != K, it takes the full path, sees
RecoveryInProgress() == false, scans ProcArray (which does not contain the
KnownAssignedXids entry), and sets MyProc->xmin = TransactionXmin = xmax.
3. Within the same transaction, the backend calls
GetSnapshotData(&CatalogSnapshotData). GetSnapshotDataReuse() sees
curXactCompletionCount == snapshot->snapXactCompletionCount (both K) and
reuses the pre-promotion snapshot. This leaves takenDuringRecovery = true
and sets RecentXmin = snapshot->xmin (< TransactionXmin), tripping
Assert(TransactionIdPrecedesOrEquals(TransactionXmin, RecentXmin)).

In non-assert builds, reusing the pre-promotion snapshot also leaves
takenDuringRecovery stale and regresses RecentXmin behind MyProc->xmin.

Fix
---

Patch 0001 rejects snapshot reuse in GetSnapshotDataReuse() if the cached
snapshot was taken during recovery and RecoveryInProgress() is now false:

if (unlikely(snapshot->takenDuringRecovery) && !RecoveryInProgress())
return false;
Assert(snapshot->takenDuringRecovery || !RecoveryInProgress());

Because a cluster cannot re-enter recovery, we only need to call
RecoveryInProgress() when snapshot->takenDuringRecovery is true, adding zero
function-call overhead on primaries. Once RecoveryInProgress() observes
RECOVERY_STATE_DONE in a backend, LocalRecoveryInProgress stays false for the
lifetime of that backend, so no subsequent GetSnapshotDataReuse() call in the
same backend can reuse a pre-promotion snapshot after a post-promotion snapshot
has set TransactionXmin.

I also considered advancing xactCompletionCount earlier in StartupXLOG(), but
that would still leave a window between releasing XLogCtl->info_lck and
acquiring ProcArrayLock exclusively (and we should not acquire ProcArrayLock
while holding ControlFileLock / updating the control file). Checking
takenDuringRecovery in GetSnapshotDataReuse() closes the window directly with
no extra locking.

Patch 0002 adds an optional deterministic TAP test
(src/test/recovery/t/062_snapshot_reuse_promotion.pl) using a new injection
point ("promotion-before-shutdown-recovery") right before
ShutdownRecoveryTransactionEnvironment() in StartupXLOG(). Without 0001, the
test deterministically reproduces the exact assertion failure at
procarray.c:2071; with 0001, it passes.

0001 is standalone and backpatches cleanly through REL_15_STABLE (all supported
branches; the bug has existed since 623a9ba79bb in PostgreSQL 14). 0002 is
intended for master (or back to 17 where injection points exist) if an
injection-point test is desired.

[1] https://github.com/postgres/postgres-cfbot/actions/runs/46220848694/job/141215415824

Hannu Krosing (2):
Do not reuse recovery snapshots after recovery ends
Add TAP test for snapshot reuse during promotion

src/backend/access/transam/xlog.c | 2 +
src/backend/storage/ipc/procarray.c | 18 +++
src/test/recovery/meson.build | 1 +
src/test/recovery/t/062_snapshot_reuse_promotion.pl | 123 ++++++++++++++++++
4 files changed, 144 insertions(+)
create mode 100644 src/test/recovery/t/062_snapshot_reuse_promotion.pl

Attachment Content-Type Size
v1-0001-Do-not-reuse-recovery-snapshots-after-recovery-en.patch application/x-patch 2.9 KB
v1-0002-Add-TAP-test-for-snapshot-reuse-during-promotion.patch application/x-patch 6.9 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message Masahiko Sawada 2026-12-02 18:49:59 Re: Fix LogStandbySnapshot() race during logical decoding activation
Previous Message Alexander Nestorov 2026-12-02 18:39:27 Re: [PATCH] btree_gist: add cross-type integer operator support for GiST