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
From 7d346f85bcea6259a93bfc6e26e4c22ad07d7be3 Mon Sep 17 00:00:00 2001
From: Hannu Krosing <[email protected]>
Date: Wed, 2 Dec 2026 10:19:12 +0000
Subject: [PATCH v1 1/2] Do not reuse recovery snapshots after recovery ends

During promotion in StartupXLOG(), XLogCtl->SharedRecoveryState is
switched to RECOVERY_STATE_DONE before
ShutdownRecoveryTransactionEnvironment() calls
ExpireAllKnownAssignedTransactionIds() (which advances
TransamVariables->xactCompletionCount).

In that window, RecoveryInProgress() already returns false while
xactCompletionCount has not yet changed.  If a backend has a cached
static SnapshotData (such as CatalogSnapshotData) built before
promotion with takenDuringRecovery = true and an older xmin from
KnownAssignedXids, and then builds another snapshot fresh after
SharedRecoveryState flips (reading ProcArray and setting a newer
TransactionXmin), a subsequent GetSnapshotData() call for the cached
snapshot will reuse the pre-promotion snapshot via
GetSnapshotDataReuse().  This leaves takenDuringRecovery stale and
moves RecentXmin backwards past TransactionXmin, tripping
Assert(TransactionIdPrecedesOrEquals(TransactionXmin, RecentXmin)).

Reject snapshot reuse in GetSnapshotDataReuse() when the cached
snapshot was taken during recovery and RecoveryInProgress() is now
false.  Because recovery cannot be re-entered, we only need to call
RecoveryInProgress() when snapshot->takenDuringRecovery is true,
avoiding any extra overhead on primaries.

Backpatch-through: 15
---
 src/backend/storage/ipc/procarray.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c
index 230663d1352..7653f276171 100644
--- a/src/backend/storage/ipc/procarray.c
+++ b/src/backend/storage/ipc/procarray.c
@@ -2044,6 +2044,24 @@ GetSnapshotDataReuse(Snapshot snapshot)
 	if (curXactCompletionCount != snapshot->snapXactCompletionCount)
 		return false;
 
+	/*
+	 * Do not reuse a snapshot taken during recovery once recovery has ended.
+	 * During promotion, StartupXLOG() sets SharedRecoveryState to
+	 * RECOVERY_STATE_DONE before ShutdownRecoveryTransactionEnvironment()
+	 * calls ExpireAllKnownAssignedTransactionIds() to advance
+	 * xactCompletionCount.  In that window, a newly built snapshot reads
+	 * ProcArray while a cached pre-promotion snapshot still reflects
+	 * KnownAssignedXids, which can have an older xmin (violating
+	 * TransactionXmin <= RecentXmin) and leaves takenDuringRecovery stale.
+	 *
+	 * Since recovery cannot be re-entered, we only need to call
+	 * RecoveryInProgress() when the cached snapshot was taken during
+	 * recovery.
+	 */
+	if (unlikely(snapshot->takenDuringRecovery) && !RecoveryInProgress())
+		return false;
+	Assert(snapshot->takenDuringRecovery || !RecoveryInProgress());
+
 	/*
 	 * 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
-- 
2.56.1.911.g883d8bcb20-goog

From 0e22bfd69c726c7447992bd603fd265f6e90338c Mon Sep 17 00:00:00 2001
From: Hannu Krosing <[email protected]>
Date: Wed, 2 Dec 2026 10:19:12 +0000
Subject: [PATCH v1 2/2] Add TAP test for snapshot reuse during promotion

Add an injection point in StartupXLOG() between switching
SharedRecoveryState to RECOVERY_STATE_DONE and calling
ShutdownRecoveryTransactionEnvironment(), and a recovery TAP test
verifying that GetSnapshotDataReuse() does not reuse a cached
pre-promotion snapshot during that window.
---
 src/backend/access/transam/xlog.c             |   2 +
 src/test/recovery/meson.build                 |   1 +
 .../t/062_snapshot_reuse_promotion.pl         | 123 ++++++++++++++++++
 3 files changed, 126 insertions(+)
 create mode 100644 src/test/recovery/t/062_snapshot_reuse_promotion.pl

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index fd37ea4f607..f9a8eb71c89 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -6959,6 +6959,8 @@ StartupXLOG(void)
 	 * particularly critical for prepared 2PC transactions, that would still
 	 * need to be included in snapshots once recovery has ended.
 	 */
+	INJECTION_POINT("promotion-before-shutdown-recovery", NULL);
+
 	if (standbyState != STANDBY_DISABLED)
 		ShutdownRecoveryTransactionEnvironment();
 
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cb3df6ed895..bd3030cd48e 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
       't/059_remote_apply_status_interval.pl',
       't/060_multixact_crashed_updater.pl',
       't/061_recovery_target_prefetch.pl',
+      't/062_snapshot_reuse_promotion.pl',
     ],
   },
 }
diff --git a/src/test/recovery/t/062_snapshot_reuse_promotion.pl b/src/test/recovery/t/062_snapshot_reuse_promotion.pl
new file mode 100644
index 00000000000..031a1402647
--- /dev/null
+++ b/src/test/recovery/t/062_snapshot_reuse_promotion.pl
@@ -0,0 +1,123 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that a backend does not reuse a cached snapshot taken during recovery
+# after SharedRecoveryState transitions to RECOVERY_STATE_DONE during promotion,
+# before ShutdownRecoveryTransactionEnvironment() advances xactCompletionCount.
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+plan skip_all => 'Injection points not supported by this build'
+  unless $ENV{enable_injection_points} eq 'yes';
+
+my $node_primary = PostgreSQL::Test::Cluster->new('primary');
+$node_primary->init(allows_streaming => 1);
+$node_primary->start;
+
+if (!$node_primary->check_extension('injection_points'))
+{
+	plan skip_all => 'Extension injection_points not installed';
+}
+
+$node_primary->safe_psql(
+	'postgres', q(
+	CREATE EXTENSION injection_points;
+	CREATE TABLE t1 (i int);
+	CREATE TABLE t2 (i int);
+	INSERT INTO t1 VALUES (1);
+	INSERT INTO t2 VALUES (2);
+));
+
+$node_primary->backup('my_backup');
+
+my $node_standby = PostgreSQL::Test::Cluster->new('standby');
+$node_standby->init_from_backup($node_primary, 'my_backup',
+	has_streaming => 1);
+$node_standby->start;
+
+# Hold an uncommitted transaction with an XID on the primary so that
+# KnownAssignedXids on the standby contains an XID strictly older than
+# latestCompletedXid + 1.
+my $p_uncommitted = $node_primary->background_psql('postgres');
+$p_uncommitted->query_safe('BEGIN; INSERT INTO t1 VALUES (100);');
+
+# Commit a newer transaction so latestCompletedXid advances past the
+# uncommitted XID, and wait for the standby to replay it.
+$node_primary->safe_psql('postgres', 'INSERT INTO t1 VALUES (200);');
+$node_primary->wait_for_replay_catchup($node_standby);
+
+# Open a session on the standby.  First take CurrentSnapshotData inside a
+# REPEATABLE READ transaction at xactCompletionCount = K - 1.
+my $s1 = $node_standby->background_psql('postgres');
+$s1->query_safe(
+	'BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM t1;');
+
+# Commit another transaction on the primary that also invalidates catalog
+# snapshots (via DDL), advancing xactCompletionCount to K.
+$node_primary->safe_psql('postgres', 'CREATE TABLE t3 (i int);');
+$node_primary->wait_for_replay_catchup($node_standby);
+
+# Still inside the REPEATABLE READ transaction on s1: query t3.  Because
+# REPEATABLE READ keeps the existing transaction snapshot, CurrentSnapshotData
+# stays at K - 1, while the DDL invalidation forces GetCatalogSnapshot() ->
+# GetSnapshotData(&CatalogSnapshotData) to rebuild CatalogSnapshotData at K
+# with takenDuringRecovery = true and xmin = <uncommitted XID>.
+$s1->query_safe('SELECT count(*) FROM t3;');
+$s1->query_safe('COMMIT;');
+
+# Attach the injection point on the standby so promotion pauses after
+# SharedRecoveryState = RECOVERY_STATE_DONE and before
+# ShutdownRecoveryTransactionEnvironment().
+$node_standby->safe_psql('postgres',
+	"SELECT injection_points_attach('promotion-before-shutdown-recovery', 'wait');"
+);
+
+# Trigger promotion asynchronously (do not wait for completion) and wait
+# until the startup process pauses at the injection point.
+$node_standby->safe_psql('postgres', 'SELECT pg_promote(false);');
+$node_standby->wait_for_event('startup',
+	'promotion-before-shutdown-recovery');
+
+# Now we are in the promotion window: RecoveryInProgress() is false, while
+# xactCompletionCount is still K.  In s1:
+# 1. BEGIN + SELECT count(*) FROM t1 builds CurrentSnapshotData fresh (since
+#    its cached snapXactCompletionCount is K - 1 != K), setting TransactionXmin = xmax.
+# 2. SELECT count(*) FROM t2 (uncached relation) calls GetCatalogSnapshot() ->
+#    GetSnapshotData(&CatalogSnapshotData), which has snapXactCompletionCount == K
+#    and takenDuringRecovery == true (xmin = <uncommitted XID> < TransactionXmin).
+# Without the fix, GetSnapshotDataReuse() reuses CatalogSnapshotData and trips
+# Assert(TransactionIdPrecedesOrEquals(TransactionXmin, RecentXmin)).
+my $res = $s1->query_safe(
+	q(
+	BEGIN;
+	SELECT count(*) FROM t1;
+	SELECT count(*) FROM t2;
+	COMMIT;
+));
+is($res, "2\n1",
+	'queries during promotion window succeed without stale snapshot reuse');
+
+# Release the startup process and wait for promotion (including
+# ShutdownRecoveryTransactionEnvironment()) to complete.  Note that
+# pg_is_in_recovery() already returns false at the injection point, so wait
+# for the startup process itself to exit.
+$node_standby->safe_psql('postgres',
+	"SELECT injection_points_wakeup('promotion-before-shutdown-recovery');"
+);
+$node_standby->safe_psql('postgres',
+	"SELECT injection_points_detach('promotion-before-shutdown-recovery');"
+);
+$node_standby->poll_query_until('postgres',
+	"SELECT count(*) = 0 FROM pg_stat_activity WHERE backend_type = 'startup';"
+) or die "standby did not finish promotion";
+
+$s1->quit;
+$p_uncommitted->query_safe('ROLLBACK;');
+$p_uncommitted->quit;
+$node_standby->stop;
+$node_primary->stop;
+
+done_testing();
-- 
2.56.1.911.g883d8bcb20-goog

Reply via email to