Hi,

While testing the dynamic logical decoding status control, I noticed another race condition in LogStandbySnapshot(), when logical decoding is concurrently enabled, ProcArrayLock can be released before logging the xl_running_xacts WAL record, causing historic snapshot corruption. The process is as follows:

1. S1 calls GetRunningTransactionData() while T1 (XID 800, e.g., CREATE TABLE tab_snap) is still in ProcArray, so S1 computes oldestRunningXid = 800 in memory. 2. S1 releases ProcArrayLock early, before writing its xl_running_xacts record to WAL. 3. T1 commits: it writes COMMIT 800 at LSN 100 and finishes ProcArrayEndTransaction(), removing 800 from ProcArray. (Had S1 kept ProcArrayLock, T1 would have blocked here.) 4. S2 runs LogStandbySnapshot(): since 800 is already gone from ProcArray, S2 computes oldestRunningXid = 801 (nextXid) and writes its xl_running_xacts record at LSN 200. 5. S1 writes its delayed xl_running_xacts record at LSN 300 with the stale oldestRunningXid = 800.

Replaying that out-of-order WAL stream corrupts SnapBuild's state:
- LSN 100 (COMMIT 800): SnapBuild adds 800 to builder->committed.xip and sets builder->xmax = 801. - LSN 200 (S2's RUNNING_XACTS, oldestRunningXid = 801): SnapBuild sets builder->xmin = 801 and purges 800 from builder->committed.xip. - LSN 300 (S1's RUNNING_XACTS, oldestRunningXid = 800): SnapBuild overwrites builder->xmin = 800. Now 800 is back inside [xmin, xmax) after already being purged from committed.xip, so subsequent historic snapshots built by SnapBuild mark committed transaction 800 as still in progress (e.g., failing with "ERROR: pg_attribute catalog is missing 1 attribute(s) for relation OID ..." or "ERROR: could not map filenumber ... to relation OID").

Currently, LogStandbySnapshot() checks IsLogicalDecodingEnabled() (logical_decoding_enabled) to decide whether to keep ProcArrayLock. However, enabling logical decoding happens in two phases:

1. EnableLogicalDecoding() sets xlog_logical_info = true and waits for
   all processes to absorb a ProcSignalBarrier.
2. Only after that barrier wait finishes does it set
   logical_decoding_enabled = true, after which the caller reserves the
   new slot's restart_lsn.

If S1 absorbs the barrier in phase 1 and then calls LogStandbySnapshot() before phase 2 sets logical_decoding_enabled = true, IsLogicalDecodingEnabled() still returns false, so S1 releases ProcArrayLock early. Meanwhile, since S1 has already absorbed the barrier, the activating backend does not wait for S1: it can finish phase 2 and reserve the new slot's restart_lsn before S1 writes its xl_running_xacts record, exposing that out-of-order record to logical decoding.

Attached is a patch set to fix this:

0001 checks IsXLogLogicalInfoEnabled() right before GetRunningTransactionData() (not while holding ProcArrayLock, to respect the lock ordering with DisableLogicalDecoding()). If xlog_logical_info is still false at that point, neither GetRunningTransactionData() nor LogCurrentRunningXacts() processes ProcSignalBarriers, so no concurrent activation can finish its barrier wait until after the WAL record is inserted.

0002 adds injection point to reproduce/test the above case. I kept this in a separate patch because it looks complicate and might not be worth pushing.

--
Best Regards,
Zhijie Hou
From f3e8b91b57c82acb24c486d5201ffdadd75958f4 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Mon, 23 Nov 2026 01:04:26 +0800
Subject: [PATCH v1 2/2] Add test for LogStandbySnapshot() race when enabling
 logical decoding.

Add an injection point in LogStandbySnapshot() and TAP tests in
051_effective_wal_level.pl verifying that ProcArrayLock is held across
LogCurrentRunningXacts() when logical decoding activation is in progress
(including when the caller's process-local XLogLogicalInfo update is
deferred in an XID-assigned transaction), preventing out-of-order
xl_running_xacts records from corrupting historic snapshots.

Author: Zhijie Hou <[email protected]>
Backpatch-through: 19
---
 src/backend/storage/ipc/standby.c             |   4 +
 .../recovery/t/051_effective_wal_level.pl     | 210 +++++++++++++++++-
 2 files changed, 204 insertions(+), 10 deletions(-)

diff --git a/src/backend/storage/ipc/standby.c 
b/src/backend/storage/ipc/standby.c
index b4bfa205262..f0af564c839 100644
--- a/src/backend/storage/ipc/standby.c
+++ b/src/backend/storage/ipc/standby.c
@@ -1302,6 +1302,8 @@ LogStandbySnapshot(void)
        }
 #endif
 
+       INJECTION_POINT_LOAD("log-standby-snapshot-before-insert");
+
        /*
         * Get details of any AccessExclusiveLocks being held at the moment.
         */
@@ -1350,6 +1352,8 @@ LogStandbySnapshot(void)
        if (!xlog_logical_info)
                LWLockRelease(ProcArrayLock);
 
+       INJECTION_POINT_CACHED("log-standby-snapshot-before-insert", NULL);
+
        recptr = LogCurrentRunningXacts(running);
 
        /* Release lock if we kept it longer ... */
diff --git a/src/test/recovery/t/051_effective_wal_level.pl 
b/src/test/recovery/t/051_effective_wal_level.pl
index 5129e6eb638..9ece6e55965 100644
--- a/src/test/recovery/t/051_effective_wal_level.pl
+++ b/src/test/recovery/t/051_effective_wal_level.pl
@@ -8,6 +8,7 @@ use warnings FATAL => 'all';
 use PostgreSQL::Test::Cluster;
 use PostgreSQL::Test::Utils;
 use Test::More;
+use Time::HiRes qw(usleep);
 
 # Check both wal_level and effective_wal_level values on the given node
 # are expected.
@@ -45,6 +46,51 @@ sub quit_and_wait
        ) or die "timed out waiting for backend $backend_pid to exit";
 }
 
+# Wait on an existing session ($psql_ctl) until $snap_pid reaches
+# log-standby-snapshot-before-insert, as new backends block in ProcArrayAdd()
+# while ProcArrayLock is held.
+sub wait_for_snapshot_before_insert
+{
+       my ($psql_ctl, $snap_pid) = @_;
+       my $max_attempts = 10 * $PostgreSQL::Test::Utils::timeout_default;
+       my $reached = '';
+
+       for (my $i = 0; $i < $max_attempts; $i++)
+       {
+               $reached = $psql_ctl->query_safe(
+                       qq[select wait_event = 
'log-standby-snapshot-before-insert' from pg_stat_activity where pid = 
$snap_pid],
+                       verbose => 0);
+               last if $reached eq 't';
+               usleep(100_000);
+       }
+       die "timed out waiting for log-standby-snapshot-before-insert"
+         unless $reached eq 't';
+}
+
+# Commit $psql_xact and verify via $psql_ctl that it blocks on ProcArrayLock.
+sub check_commit_waits_on_procarray
+{
+       my ($psql_ctl, $psql_xact, $xact_pid, $msg) = @_;
+       my $max_attempts = 10 * $PostgreSQL::Test::Utils::timeout_default;
+
+       $psql_xact->query_until(
+               qr/commit_xact/,
+               q(\echo commit_xact
+commit;
+));
+
+       my $state = '';
+       for (my $i = 0; $i < $max_attempts; $i++)
+       {
+               $state = $psql_ctl->query_safe(
+                       qq[select case when wait_event = 'ProcArray' then 
'waiting' when state = 'idle' then 'committed' end from pg_stat_activity where 
pid = $xact_pid],
+                       verbose => 0);
+               last if $state ne '';
+               usleep(100_000);
+       }
+       is($state, 'waiting', $msg);
+}
+
 # Initialize the primary server with wal_level = 'replica'.
 my $primary = PostgreSQL::Test::Cluster->new('primary');
 $primary->init(allows_streaming => 1);
@@ -561,17 +607,9 @@ select pg_cancel_backend(pid) from pg_stat_activity where 
query ~ 'slot_canceled
 
        quit_and_wait($primary, $psql_create_slot, $psql_create_slot_pid);
 
-       # Test races between the deactivation of logical decoding and slot
-       # creation during recovery. Logical decoding can be deactivated while a
-       # logical slot is being created on a standby, either by replaying an
-       # XLOG_LOGICAL_DECODING_STATUS_CHANGE record or by the end-of-recovery
-       # transition upon promotion. Slot creation paths must detect the
-       # deactivation after creating their slot and fail cleanly, instead
-       # of leaving a slot that cannot be decoded.
-
        # Restore the disabled state, and disable autovacuum so that the primary
-       # assigns no XIDs, keeping the slot synchronization test below
-       # deterministic.
+       # assigns no XIDs, keeping the snapshot and slot synchronization tests
+       # below deterministic.
        $primary->safe_psql('postgres',
                qq[select pg_drop_replication_slot('test_slot2')]);
        wait_for_logical_decoding_disabled($primary);
@@ -581,6 +619,158 @@ alter system set autovacuum = off;
 select pg_reload_conf();
 ]);
 
+       # Test that LogStandbySnapshot() holds ProcArrayLock across
+       # LogCurrentRunningXacts() when logical decoding activation is in
+       # progress (after the caller has absorbed the ProcSignalBarrier while
+       # logical_decoding_enabled is still false), preventing out-of-order
+       # xl_running_xacts records from corrupting historic snapshots.
+       my $psql_snap = $primary->background_psql('postgres');
+       my $psql_snap_pid = $psql_snap->query_safe('select pg_backend_pid()');
+       my $psql_xact = $primary->background_psql('postgres');
+       my $psql_xact_pid = $psql_xact->query_safe('select pg_backend_pid()');
+       my $psql_act = $primary->background_psql('postgres');
+       my $psql_act_pid = $psql_act->query_safe('select pg_backend_pid()');
+       # Keep a control session open before GetRunningTransactionData() 
acquires
+       # ProcArrayLock, as new backend startups wait on it in ProcArrayAdd().
+       my $psql_ctl = $primary->background_psql('postgres');
+
+       $psql_snap->query_safe(q[select injection_points_set_local()]);
+       $psql_act->query_safe(q[select injection_points_set_local()]);
+
+       # Case 1: Activation pauses at logical-decoding-activation
+       # (xlog_logical_info is true and all backends have absorbed the barrier,
+       # while logical_decoding_enabled is still false). LogStandbySnapshot()
+       # starts in that window and pauses before LogCurrentRunningXacts(), then
+       # activation finishes and reserves the slot's restart_lsn before the WAL
+       # record is inserted.
+       $psql_act->query_safe(
+               q[select injection_points_attach('logical-decoding-activation', 
'wait');]
+       );
+       $psql_act->query_until(
+               qr/start_act1/,
+               q(\echo start_act1
+select pg_create_logical_replication_slot('test_slot_snap', 'test_decoding');
+));
+       $primary->wait_for_event('client backend', 
'logical-decoding-activation');
+
+       $psql_xact->query_safe(
+               q[begin; create table tab_snap (a int); insert into tab_snap 
values (1);]
+       );
+       $psql_snap->query_safe(
+               q[select 
injection_points_attach('log-standby-snapshot-before-insert', 'wait');]
+       );
+       $psql_snap->query_until(
+               qr/start_snap1/,
+               q(\echo start_snap1
+select pg_log_standby_snapshot();
+));
+       wait_for_snapshot_before_insert($psql_ctl, $psql_snap_pid);
+
+       # Let activation finish enabling logical decoding and reserve the slot's
+       # restart_lsn while $psql_snap has not yet logged its xl_running_xacts.
+       $psql_ctl->query_safe(
+               q[
+select injection_points_detach('logical-decoding-activation');
+select injection_points_wakeup('logical-decoding-activation');
+]);
+
+       check_commit_waits_on_procarray($psql_ctl, $psql_xact, $psql_xact_pid,
+               "commit waits on ProcArrayLock when LogStandbySnapshot() 
started during activation"
+       );
+
+       # Wake $psql_snap and verify that subsequent catalog changes and 
decoding
+       # do not see a backwards xmin retreat.
+       $psql_ctl->query_safe(
+               q[
+select injection_points_detach('log-standby-snapshot-before-insert');
+select injection_points_wakeup('log-standby-snapshot-before-insert');
+]);
+       $psql_snap->query_safe('');
+       $psql_xact->query_safe('');
+       $psql_act->query_safe('');
+
+       $primary->safe_psql(
+               'postgres', qq[
+alter table tab_snap add column b int;
+insert into tab_snap values (2, 3);
+]);
+       like(
+               $primary->safe_psql(
+                       'postgres',
+                       qq[select string_agg(data, E'\n') from 
pg_logical_slot_get_changes('test_slot_snap', null, null)]
+               ),
+               qr/table public\.tab_snap: INSERT: a\[integer\]:2 
b\[integer\]:3/,
+               "decoding succeeds without historic snapshot corruption");
+
+       $primary->safe_psql(
+               'postgres', qq[
+drop table tab_snap;
+select pg_drop_replication_slot('test_slot_snap');
+]);
+       wait_for_logical_decoding_disabled($primary);
+
+       # Case 2: $psql_snap already has an assigned XID before activation
+       # starts, so its process-local XLogLogicalInfo update is deferred; it
+       # must still hold ProcArrayLock based on shared xlog_logical_info.
+       $psql_snap->query_safe(q[begin; select pg_current_xact_id();]);
+
+       $psql_act->query_safe(
+               q[select injection_points_attach('logical-decoding-activation', 
'wait');]
+       );
+       $psql_act->query_until(
+               qr/start_act2/,
+               q(\echo start_act2
+select pg_create_logical_replication_slot('test_slot_snap', 'test_decoding');
+));
+       $primary->wait_for_event('client backend', 
'logical-decoding-activation');
+
+       $psql_xact->query_safe(q[begin; select pg_current_xact_id();]);
+       $psql_snap->query_safe(
+               q[select 
injection_points_attach('log-standby-snapshot-before-insert', 'wait');]
+       );
+       $psql_snap->query_until(
+               qr/start_snap2/,
+               q(\echo start_snap2
+select pg_log_standby_snapshot();
+));
+       wait_for_snapshot_before_insert($psql_ctl, $psql_snap_pid);
+
+       check_commit_waits_on_procarray($psql_ctl, $psql_xact, $psql_xact_pid,
+               "commit waits on ProcArrayLock when caller's local 
XLogLogicalInfo update is deferred"
+       );
+
+       $psql_ctl->query_safe(
+               q[
+select injection_points_detach('log-standby-snapshot-before-insert');
+select injection_points_wakeup('log-standby-snapshot-before-insert');
+]);
+       $psql_snap->query_safe('commit');
+       $psql_xact->query_safe('');
+
+       $psql_ctl->query_safe(
+               q[
+select injection_points_detach('logical-decoding-activation');
+select injection_points_wakeup('logical-decoding-activation');
+]);
+       $psql_act->query_safe('');
+
+       $psql_ctl->quit;
+       $psql_xact->quit;
+       quit_and_wait($primary, $psql_snap, $psql_snap_pid);
+       quit_and_wait($primary, $psql_act, $psql_act_pid);
+
+       $primary->safe_psql('postgres',
+               qq[select pg_drop_replication_slot('test_slot_snap')]);
+       wait_for_logical_decoding_disabled($primary);
+
+       # Test races between the deactivation of logical decoding and slot
+       # creation during recovery. Logical decoding can be deactivated while a
+       # logical slot is being created on a standby, either by replaying an
+       # XLOG_LOGICAL_DECODING_STATUS_CHANGE record or by the end-of-recovery
+       # transition upon promotion. Slot creation paths must detect the
+       # deactivation after creating their slot and fail cleanly, instead
+       # of leaving a slot that cannot be decoded.
+
        # Initialize standby5 node, setting up the requirements for slot
        # synchronization.
        $primary->safe_psql('postgres',
-- 
2.54.0 (Apple Git-157)

From c90220167e0033b53b8a55a1eeecfc71aadea16e Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Mon, 23 Nov 2026 01:44:05 +0800
Subject: [PATCH v1 1/2] Fix LogStandbySnapshot() race when enabling logical
 decoding.

When logical decoding is active, LogStandbySnapshot() must hold
ProcArrayLock until LogCurrentRunningXacts() inserts the
xl_running_xacts record into WAL. Otherwise, a committing transaction
listed in that record can finish ProcArrayEndTransaction() first,
allowing a concurrent LogStandbySnapshot() to log a newer
oldestRunningXid ahead of the stale one in WAL. Replaying those
out-of-order xl_running_xacts records during logical decoding moves
SnapBuild's xmin backwards after older committed catalog transactions
have already been purged, corrupting historic snapshots.

Commit 67c20979ce7 made LogStandbySnapshot() check
IsLogicalDecodingEnabled() to decide whether to keep ProcArrayLock.
However, EnableLogicalDecoding() first sets xlog_logical_info = true
and waits for all processes to absorb a ProcSignalBarrier, and only
afterwards sets logical_decoding_enabled = true. If a process absorbs
that barrier and then enters LogStandbySnapshot() before
logical_decoding_enabled is set to true, it sees
logical_decoding_enabled = false and releases ProcArrayLock early,
while the activating backend can finish enabling logical decoding and
reserve the new slot's restart_lsn before LogCurrentRunningXacts()
writes the WAL record.

Fix this by checking IsXLogLogicalInfoEnabled() right before
GetRunningTransactionData() (not while holding ProcArrayLock, to avoid
a three-way deadlock with DisableLogicalDecoding() and
CreateInitDecodingContext()). Checking shared xlog_logical_info rather
than logical_decoding_enabled or the process-local XLogLogicalInfo
cache covers both in-progress activations and callers in XID-assigned
transactions whose local cache update is deferred; if it is still false
at that point, neither GetRunningTransactionData() nor
LogCurrentRunningXacts() processes ProcSignalBarriers, so no concurrent
activation can finish its barrier wait until after the WAL record is
inserted.

Author: Zhijie Hou <[email protected]>
Backpatch-through: 19
---
 src/backend/storage/ipc/standby.c | 25 ++++++++++++++++++++++---
 1 file changed, 22 insertions(+), 3 deletions(-)

diff --git a/src/backend/storage/ipc/standby.c 
b/src/backend/storage/ipc/standby.c
index 7f011e04990..b4bfa205262 100644
--- a/src/backend/storage/ipc/standby.c
+++ b/src/backend/storage/ipc/standby.c
@@ -1287,7 +1287,7 @@ LogStandbySnapshot(void)
        RunningTransactions running;
        xl_standby_lock *locks;
        int                     nlocks;
-       bool            logical_decoding_enabled = IsLogicalDecodingEnabled();
+       bool            xlog_logical_info;
 
        Assert(XLogStandbyInfoActive());
 
@@ -1310,6 +1310,17 @@ LogStandbySnapshot(void)
                LogAccessExclusiveLocks(nlocks, locks);
        pfree(locks);
 
+       /*
+        * Check whether logical WAL logging is enabled before
+        * GetRunningTransactionData() acquires ProcArrayLock.
+        * IsXLogLogicalInfoEnabled() acquires LogicalDecodingControlLock, so
+        * calling it while holding ProcArrayLock could cause a three-way 
deadlock
+        * with DisableLogicalDecoding() (which takes LogicalDecodingControlLock
+        * before ReplicationSlotControlLock) and e.g. 
CreateInitDecodingContext()
+        * (which takes ReplicationSlotControlLock before ProcArrayLock).
+        */
+       xlog_logical_info = IsXLogLogicalInfoEnabled();
+
        /*
         * Log details of all in-progress transactions. This should be the last
         * record we write, because standby will open up when it sees this.
@@ -1327,14 +1338,22 @@ LogStandbySnapshot(void)
         * which, according to the WAL, has committed before the 
xl_running_xacts
         * record. Fortunately this routine isn't executed frequently, and it's
         * only a shared lock.
+        *
+        * Check shared xlog_logical_info (sampled above) so we also keep the 
lock
+        * while logical decoding is being enabled, or when this backend's local
+        * XLogLogicalInfo update is delayed until transaction end. If
+        * xlog_logical_info was false, no concurrent activation can finish its
+        * ProcSignalBarrier wait until LogCurrentRunningXacts() inserts the WAL
+        * record, since neither GetRunningTransactionData() nor
+        * LogCurrentRunningXacts() processes barriers.
         */
-       if (!logical_decoding_enabled)
+       if (!xlog_logical_info)
                LWLockRelease(ProcArrayLock);
 
        recptr = LogCurrentRunningXacts(running);
 
        /* Release lock if we kept it longer ... */
-       if (logical_decoding_enabled)
+       if (xlog_logical_info)
                LWLockRelease(ProcArrayLock);
 
        /* GetRunningTransactionData() acquired XidGenLock, we must release it 
*/
-- 
2.54.0 (Apple Git-157)

Reply via email to