pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
59+ messages / 11 participants
[nested] [flat]

Commits from this thread:
  2026-11-06 92a74e26bb b175cbae02  Detach injection point at the end of repack_dropped isolation test.
  2026-11-06 f1e25929e2 9c8418d014  Stabilize 051_effective_wal_level.pl.
  2026-10-08 d64e535748 d53e54f5e5  Stabilize recently added tests in 051_effective_wal_level.pl.
  2026-10-07 1f2245371e 3f5bfbce4c  Fix slotsync when logical decoding is disabled and re-enabled.
  2026-10-07 952cb07913 5412127cbf  Add an init callback for the logical decoding control data.
  2026-07-30 18f9785e0b 5c808b8c5c  Fix background psql session cleanup in 051_effective_wal_level.pl.
  2026-07-30 6aba42c660 6a80179f6b  Fix races between deactivation of logical decoding and slot creation.
  2026-07-27 0fd30e2119 99e47536bb  Fix race condition when enabling logical decoding concurrently.
* Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-10 04:18  Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Srinath Reddy Sadipiralla @ 2026-07-10 04:18 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; +Cc: Masahiko Sawada <sawada.mshk@gmail.com>

Hi,

While stress-testing REPACK CONCURRENTLY, I was in that
area looking at BUG #19519 (REPACK failing with "missingchunk
number N for toast value" [0]; note that one reproduces with plain
REPACK too, since it's the shared copy_table_data() path, so
it's independent of what follows), I hit a different, reproducible
failure under high concurrency:
    ERROR:  unexpected logical decoding status change 1

I believe this is a race bug in the on-demand logical decoding
activation machinery (logicalctl.c), exposed by
REPACK CONCURRENTLY but not actually specific to it, as
this can be reproduced using pg_create_logical_replication_slot
and CREATE_REPLICATION_SLOT.

At wal_level = 'replica', logical decoding is toggled on the first time a
logical slot is created.  EnableLogicalDecoding() sets the shared
logical_decoding_enabled flag and writes an
XLOG_LOGICAL_DECODING_STATUS_CHANGE record so standbys
learn about the change.  On the decoding side, xlog_decode() treats
that record as unreachable:
elog(ERROR, "unexpected logical decoding status change %d", ...);

The reasoning (per the comment there) is that no running decoder can ever
have such a record within the LSN range it scans: there is exactly one
enable record per disabled->enabled transition, and it precedes the
decoding start point reserved by any slot.

That case does not hold under concurrency.  EnableLogicalDecoding()
does:

    LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
    if (logical_decoding_enabled)     /* already on? -> done */
        { ... return; }
    LWLockRelease(...);

    WaitForProcSignalBarrier(...);    /* lock released here */

    LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
    logical_decoding_enabled = true;
    write_logical_decoding_status_update_record(true);   /* the record */
    LWLockRelease(...);

The "already enabled?" check and the record write happen under two
separate lock acquisitions, with the barrier wait in between.  The lock
must be dropped across the barrier; backends absorbing the barrier
take LogicalDecodingControlLock in shared mode (via
IsXLogLogicalInfoEnabled()), so holding it across WaitForProcSignalBarrier()
would deadlock.

So if two backends create the first logical slot(s) at the same time,
both can pass the initial check while the flag is still false, and both
end up writing a status-change record.  The second (redundant) record
lands after the decoding start point the other slot already reserved,
so that slot scans it and trips the elog() above.

REPACK CONCURRENTLY makes this easy to hit because each operation
creates a temporary logical slot (max_repack_replication_slots), so firing
many REPACKs in parallel from the disabled state gives you many backends
racing to perform the very first activation.  But nothing here is
REPACK-specific.

To reproduce this i have added a test using logical-decoding-activation
injection point in 051_effective_wal_level.pl

I also hit it with a stress script [1] which was again related to the
BUG #19519, instead of vacuum full i replaced it with REPACK (concurrently).

To fix this I re-checked the flag after re-acquiring the lock and skipped
the state change/WAL write if another backend had already completed
the transition.

    LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);

    if (LogicalDecodingCtl->logical_decoding_enabled)
    {
        LogicalDecodingCtl->pending_disable = false;
        LWLockRelease(LogicalDecodingControlLock);
        return;
    }

    START_CRIT_SECTION();

With this, only the backend that actually performs the disabled->enabled
transition writes a record, and every slot's start point stays at or after
it, restoring the case xlog_decode() depends on.

Patch attached.  It fixes logicalctl.c and adds a regression test to
051_effective_wal_level.pl reusing the existing injection-point
infrastructure.  With the fix the test passes; without it it fails with
the exact error above.

[0] -
https://www.postgresql.org/message-id/flat/19519-fe02d8ff679d834d%40postgresql.org
[1] -
https://www.postgresql.org/message-id/18351-f6e06364b3a2e669%40postgresql.org

-- 
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/

Attachments:

v1-0001-Avoid-writing-a-redundant-logical-decoding-status-ch.patch (application/octet-stream, 7.5K) download From 235a1c590cf85636bce155c3092b1e0f95a48fc0 Mon Sep 17 00:00:00 2001 From: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Date: Fri, 10 Jul 2026 09:12:19 +0530 Subject: [PATCH 1/1] Avoid writing a redundant logical-decoding status-change record When wal_level = 'replica', logical decoding is enabled on demand the first time a logical slot is created.EnableLogicalDecoding() flips the shared logical_decoding_enabled flag and writes an XLOG_LOGICAL_DECODING_STATUS_CHANGE record to propagate the change to standbys. xlog_decode() treats that record as unreachable and errors out, on the assumption that exactly one such record is written per disabled->enabled transition and that it always precedes the decoding start point of every slot. That assumption can be violated.EnableLogicalDecoding() checks logical_decoding_enabled, then releases LogicalDecodingControlLock to wait on a ProcSignalBarrier, then re-acquires the lock to write the record.The lock must be released across the barrier wait, because the backends absorbing the barrier take it in shared mode.If two backends create the first logical slot(s) concurrently, both can observe the flag still unset before either writes the record, so both perform the transition and both emit a status-change record.The second, redundant record is written after the decoding start point that the other slot has already reserved, so that slot decodes it and fails with: ERROR: unexpected logical decoding status change 1 Fix by re-checking logical_decoding_enabled after re-acquiring the lock, and skipping the state change and the WAL write if another backend has already completed the transition.This mirrors the existing fast-path check at the top of the function. Add a regression test to 051_effective_wal_level.pl that drives the race deterministically using the logical-decoding-activation injection point. Reported-by: Srinath Reddy Sadipiralla Author: Srinath Reddy Sadipiralla --- src/backend/replication/logical/logicalctl.c | 22 ++++++ .../recovery/t/051_effective_wal_level.pl | 71 +++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index c11d1316450..40e86086954 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -384,6 +384,28 @@ EnableLogicalDecoding(void) LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Re-check whether logical decoding got enabled while we waited for the + * barrier above. We had to release the lock across the barrier wait (the + * backends absorbing the barrier take this lock in shared mode, so holding + * it here would deadlock), which means a concurrent activator may have + * completed the disabled->enabled transition in the meantime. In that + * case the WAL record has already been written and we must not write + * another one: a second, redundant XLOG_LOGICAL_DECODING_STATUS_CHANGE + * record could fall within the WAL range that a concurrently-created slot + * has already reserved as its decoding start point, and xlog_decode() + * treats such a record as unreachable and errors out. + * + * This mirrors the fast-path check at the top of this function; we simply + * have to repeat it now that we hold the lock again. + */ + if (LogicalDecodingCtl->logical_decoding_enabled) + { + LogicalDecodingCtl->pending_disable = false; + LWLockRelease(LogicalDecodingControlLock); + return; + } + START_CRIT_SECTION(); /* diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index d4bc7f0aa40..6a31a25e4a8 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -381,6 +381,77 @@ if ( $ENV{enable_injection_points} eq 'yes' test_wal_level($primary, "replica|replica", "effective_wal_level got decreased to 'replica' on primary"); + # A redundant activation must not leave a stray status-change record that a + # concurrently-created slot later decodes. Two backends racing to enable + # logical decoding can both pass the "already enabled?" check in + # EnableLogicalDecoding() while the flag is still off (the lock is released + # across the barrier wait) and each write an + # XLOG_LOGICAL_DECODING_STATUS_CHANGE record. The second, redundant record + # lands after the decoding start point already reserved by the first slot, + # which then decodes it and errors out in xlog_decode() with "unexpected + # logical decoding status change". Logical decoding is disabled here, and + # this runs before the cancellation tests below so that no stale waiter is + # left registered on the injection point (a canceled waiter is not cleaned + # up, which would misdirect injection_points_wakeup()). + + # Park one activator right after the barrier wait but before it flips the + # flag and writes the record. + my $psql_stray = $primary->background_psql('postgres'); + $psql_stray->query_until( + qr/create_slot_stray/, + q(\echo create_slot_stray +select injection_points_set_local(); +select injection_points_attach('logical-decoding-activation', 'wait'); +select pg_create_logical_replication_slot('slot_stray', 'test_decoding'); +)); + $primary->wait_for_event('client backend', 'logical-decoding-activation'); + note("injection_point 'logical-decoding-activation' is reached"); + + # A second backend enables logical decoding and finishes creating its slot, + # reserving its decoding start point after its own status-change record (so + # it never decodes its own record). + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('slot_first', 'test_decoding')] + ); + test_wal_level($primary, "replica|logical", + "logical decoding enabled by the first of two concurrent activations"); + + # Release the parked activator so it runs the rest of the activation code. + # Logical decoding is already enabled by now, so it must NOT write a second, + # redundant status-change record. In the buggy case it writes one here, + # just after slot_first's reserved decoding start point. + $primary->safe_psql('postgres', + qq[select injection_points_wakeup('logical-decoding-activation')]); + + # Let the released backend finish creating its slot: feed running-xacts + # records until it reaches a consistent point (poll_query_until re-runs the + # query, so pg_log_standby_snapshot() is called until the slot is created). + $primary->poll_query_until( + 'postgres', qq[ +select (pg_log_standby_snapshot() is not null) + and exists (select 1 from pg_replication_slots + where slot_name = 'slot_stray' and confirmed_flush_lsn is not null) +]); + $psql_stray->quit; + + # Decoding the first slot must not stumble over a stray status-change record. + my ($decode_rc, $decode_out, $decode_err) = $primary->psql( + 'postgres', + qq[select count(*) from pg_logical_slot_get_changes('slot_first', null, null)], + on_error_die => 0); + is($decode_rc, 0, "decoding a concurrently-created slot succeeds"); + unlike( + $decode_err, + qr/unexpected logical decoding status change/, + "no redundant status-change record was decoded"); + + # Restore the disabled state for the tests that follow. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('slot_stray')]); + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('slot_first')]); + wait_for_logical_decoding_disabled($primary); + # Start a psql session to test the case where the activation process is # interrupted. my $psql_create_slot = $primary->background_psql('postgres'); -- 2.43.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Fwd: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-10 04:22  Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  parent: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Srinath Reddy Sadipiralla @ 2026-07-10 04:22 UTC (permalink / raw)
  To: pgsql-hackers

---------- Forwarded message ---------
From: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Date: Fri, Jul 10, 2026 at 9:48 AM
Subject: Fix "unexpected logical decoding status change" error; from
concurrent logical decoding activation
To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>
Cc: Masahiko Sawada <sawada.mshk@gmail.com>


Hi,

While stress-testing REPACK CONCURRENTLY, I was in that
area looking at BUG #19519 (REPACK failing with "missingchunk
number N for toast value" [0]; note that one reproduces with plain
REPACK too, since it's the shared copy_table_data() path, so
it's independent of what follows), I hit a different, reproducible
failure under high concurrency:
    ERROR:  unexpected logical decoding status change 1

I believe this is a race bug in the on-demand logical decoding
activation machinery (logicalctl.c), exposed by
REPACK CONCURRENTLY but not actually specific to it, as
this can be reproduced using pg_create_logical_replication_slot
and CREATE_REPLICATION_SLOT.

At wal_level = 'replica', logical decoding is toggled on the first time a
logical slot is created.  EnableLogicalDecoding() sets the shared
logical_decoding_enabled flag and writes an
XLOG_LOGICAL_DECODING_STATUS_CHANGE record so standbys
learn about the change.  On the decoding side, xlog_decode() treats
that record as unreachable:
elog(ERROR, "unexpected logical decoding status change %d", ...);

The reasoning (per the comment there) is that no running decoder can ever
have such a record within the LSN range it scans: there is exactly one
enable record per disabled->enabled transition, and it precedes the
decoding start point reserved by any slot.

That case does not hold under concurrency.  EnableLogicalDecoding()
does:

    LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
    if (logical_decoding_enabled)     /* already on? -> done */
        { ... return; }
    LWLockRelease(...);

    WaitForProcSignalBarrier(...);    /* lock released here */

    LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
    logical_decoding_enabled = true;
    write_logical_decoding_status_update_record(true);   /* the record */
    LWLockRelease(...);

The "already enabled?" check and the record write happen under two
separate lock acquisitions, with the barrier wait in between.  The lock
must be dropped across the barrier; backends absorbing the barrier
take LogicalDecodingControlLock in shared mode (via
IsXLogLogicalInfoEnabled()), so holding it across WaitForProcSignalBarrier()
would deadlock.

So if two backends create the first logical slot(s) at the same time,
both can pass the initial check while the flag is still false, and both
end up writing a status-change record.  The second (redundant) record
lands after the decoding start point the other slot already reserved,
so that slot scans it and trips the elog() above.

REPACK CONCURRENTLY makes this easy to hit because each operation
creates a temporary logical slot (max_repack_replication_slots), so firing
many REPACKs in parallel from the disabled state gives you many backends
racing to perform the very first activation.  But nothing here is
REPACK-specific.

To reproduce this i have added a test using logical-decoding-activation
injection point in 051_effective_wal_level.pl

I also hit it with a stress script [1] which was again related to the
BUG #19519, instead of vacuum full i replaced it with REPACK (concurrently).

To fix this I re-checked the flag after re-acquiring the lock and skipped
the state change/WAL write if another backend had already completed
the transition.

    LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);

    if (LogicalDecodingCtl->logical_decoding_enabled)
    {
        LogicalDecodingCtl->pending_disable = false;
        LWLockRelease(LogicalDecodingControlLock);
        return;
    }

    START_CRIT_SECTION();

With this, only the backend that actually performs the disabled->enabled
transition writes a record, and every slot's start point stays at or after
it, restoring the case xlog_decode() depends on.

Patch attached.  It fixes logicalctl.c and adds a regression test to
051_effective_wal_level.pl reusing the existing injection-point
infrastructure.  With the fix the test passes; without it it fails with
the exact error above.

[0] -
https://www.postgresql.org/message-id/flat/19519-fe02d8ff679d834d%40postgresql.org
[1] -
https://www.postgresql.org/message-id/18351-f6e06364b3a2e669%40postgresql.org

-- 
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/


-- 
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/

Attachments:

v1-0001-Avoid-writing-a-redundant-logical-decoding-status-ch.patch (application/x-patch, 7.5K) download From 235a1c590cf85636bce155c3092b1e0f95a48fc0 Mon Sep 17 00:00:00 2001 From: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Date: Fri, 10 Jul 2026 09:12:19 +0530 Subject: [PATCH 1/1] Avoid writing a redundant logical-decoding status-change record When wal_level = 'replica', logical decoding is enabled on demand the first time a logical slot is created.EnableLogicalDecoding() flips the shared logical_decoding_enabled flag and writes an XLOG_LOGICAL_DECODING_STATUS_CHANGE record to propagate the change to standbys. xlog_decode() treats that record as unreachable and errors out, on the assumption that exactly one such record is written per disabled->enabled transition and that it always precedes the decoding start point of every slot. That assumption can be violated.EnableLogicalDecoding() checks logical_decoding_enabled, then releases LogicalDecodingControlLock to wait on a ProcSignalBarrier, then re-acquires the lock to write the record.The lock must be released across the barrier wait, because the backends absorbing the barrier take it in shared mode.If two backends create the first logical slot(s) concurrently, both can observe the flag still unset before either writes the record, so both perform the transition and both emit a status-change record.The second, redundant record is written after the decoding start point that the other slot has already reserved, so that slot decodes it and fails with: ERROR: unexpected logical decoding status change 1 Fix by re-checking logical_decoding_enabled after re-acquiring the lock, and skipping the state change and the WAL write if another backend has already completed the transition.This mirrors the existing fast-path check at the top of the function. Add a regression test to 051_effective_wal_level.pl that drives the race deterministically using the logical-decoding-activation injection point. Reported-by: Srinath Reddy Sadipiralla Author: Srinath Reddy Sadipiralla --- src/backend/replication/logical/logicalctl.c | 22 ++++++ .../recovery/t/051_effective_wal_level.pl | 71 +++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index c11d1316450..40e86086954 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -384,6 +384,28 @@ EnableLogicalDecoding(void) LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Re-check whether logical decoding got enabled while we waited for the + * barrier above. We had to release the lock across the barrier wait (the + * backends absorbing the barrier take this lock in shared mode, so holding + * it here would deadlock), which means a concurrent activator may have + * completed the disabled->enabled transition in the meantime. In that + * case the WAL record has already been written and we must not write + * another one: a second, redundant XLOG_LOGICAL_DECODING_STATUS_CHANGE + * record could fall within the WAL range that a concurrently-created slot + * has already reserved as its decoding start point, and xlog_decode() + * treats such a record as unreachable and errors out. + * + * This mirrors the fast-path check at the top of this function; we simply + * have to repeat it now that we hold the lock again. + */ + if (LogicalDecodingCtl->logical_decoding_enabled) + { + LogicalDecodingCtl->pending_disable = false; + LWLockRelease(LogicalDecodingControlLock); + return; + } + START_CRIT_SECTION(); /* diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index d4bc7f0aa40..6a31a25e4a8 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -381,6 +381,77 @@ if ( $ENV{enable_injection_points} eq 'yes' test_wal_level($primary, "replica|replica", "effective_wal_level got decreased to 'replica' on primary"); + # A redundant activation must not leave a stray status-change record that a + # concurrently-created slot later decodes. Two backends racing to enable + # logical decoding can both pass the "already enabled?" check in + # EnableLogicalDecoding() while the flag is still off (the lock is released + # across the barrier wait) and each write an + # XLOG_LOGICAL_DECODING_STATUS_CHANGE record. The second, redundant record + # lands after the decoding start point already reserved by the first slot, + # which then decodes it and errors out in xlog_decode() with "unexpected + # logical decoding status change". Logical decoding is disabled here, and + # this runs before the cancellation tests below so that no stale waiter is + # left registered on the injection point (a canceled waiter is not cleaned + # up, which would misdirect injection_points_wakeup()). + + # Park one activator right after the barrier wait but before it flips the + # flag and writes the record. + my $psql_stray = $primary->background_psql('postgres'); + $psql_stray->query_until( + qr/create_slot_stray/, + q(\echo create_slot_stray +select injection_points_set_local(); +select injection_points_attach('logical-decoding-activation', 'wait'); +select pg_create_logical_replication_slot('slot_stray', 'test_decoding'); +)); + $primary->wait_for_event('client backend', 'logical-decoding-activation'); + note("injection_point 'logical-decoding-activation' is reached"); + + # A second backend enables logical decoding and finishes creating its slot, + # reserving its decoding start point after its own status-change record (so + # it never decodes its own record). + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('slot_first', 'test_decoding')] + ); + test_wal_level($primary, "replica|logical", + "logical decoding enabled by the first of two concurrent activations"); + + # Release the parked activator so it runs the rest of the activation code. + # Logical decoding is already enabled by now, so it must NOT write a second, + # redundant status-change record. In the buggy case it writes one here, + # just after slot_first's reserved decoding start point. + $primary->safe_psql('postgres', + qq[select injection_points_wakeup('logical-decoding-activation')]); + + # Let the released backend finish creating its slot: feed running-xacts + # records until it reaches a consistent point (poll_query_until re-runs the + # query, so pg_log_standby_snapshot() is called until the slot is created). + $primary->poll_query_until( + 'postgres', qq[ +select (pg_log_standby_snapshot() is not null) + and exists (select 1 from pg_replication_slots + where slot_name = 'slot_stray' and confirmed_flush_lsn is not null) +]); + $psql_stray->quit; + + # Decoding the first slot must not stumble over a stray status-change record. + my ($decode_rc, $decode_out, $decode_err) = $primary->psql( + 'postgres', + qq[select count(*) from pg_logical_slot_get_changes('slot_first', null, null)], + on_error_die => 0); + is($decode_rc, 0, "decoding a concurrently-created slot succeeds"); + unlike( + $decode_err, + qr/unexpected logical decoding status change/, + "no redundant status-change record was decoded"); + + # Restore the disabled state for the tests that follow. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('slot_stray')]); + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('slot_first')]); + wait_for_logical_decoding_disabled($primary); + # Start a psql session to test the case where the activation process is # interrupted. my $psql_create_slot = $primary->background_psql('postgres'); -- 2.43.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-14 21:02  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  0 siblings, 2 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-14 21:02 UTC (permalink / raw)
  To: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: pgsql-hackers

On Thu, Jul 9, 2026 at 9:23 PM Srinath Reddy Sadipiralla
<srinath2133@gmail.com> wrote:
>
>
>
> ---------- Forwarded message ---------
> From: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
> Date: Fri, Jul 10, 2026 at 9:48 AM
> Subject: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
> To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>
> Cc: Masahiko Sawada <sawada.mshk@gmail.com>
>
>
> Hi,
>
> While stress-testing REPACK CONCURRENTLY, I was in that
> area looking at BUG #19519 (REPACK failing with "missingchunk
> number N for toast value" [0]; note that one reproduces with plain
> REPACK too, since it's the shared copy_table_data() path, so
> it's independent of what follows), I hit a different, reproducible
> failure under high concurrency:
>     ERROR:  unexpected logical decoding status change 1
>
> I believe this is a race bug in the on-demand logical decoding
> activation machinery (logicalctl.c), exposed by
> REPACK CONCURRENTLY but not actually specific to it, as
> this can be reproduced using pg_create_logical_replication_slot and CREATE_REPLICATION_SLOT.
>
> At wal_level = 'replica', logical decoding is toggled on the first time a
> logical slot is created.  EnableLogicalDecoding() sets the shared
> logical_decoding_enabled flag and writes an
> XLOG_LOGICAL_DECODING_STATUS_CHANGE record so standbys
> learn about the change.  On the decoding side, xlog_decode() treats
> that record as unreachable:
> elog(ERROR, "unexpected logical decoding status change %d", ...);
>
> The reasoning (per the comment there) is that no running decoder can ever
> have such a record within the LSN range it scans: there is exactly one
> enable record per disabled->enabled transition, and it precedes the
> decoding start point reserved by any slot.
>
> That case does not hold under concurrency.  EnableLogicalDecoding()
> does:
>
>     LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
>     if (logical_decoding_enabled)     /* already on? -> done */
>         { ... return; }
>     LWLockRelease(...);
>
>     WaitForProcSignalBarrier(...);    /* lock released here */
>
>     LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
>     logical_decoding_enabled = true;
>     write_logical_decoding_status_update_record(true);   /* the record */
>     LWLockRelease(...);
>
> The "already enabled?" check and the record write happen under two
> separate lock acquisitions, with the barrier wait in between.  The lock
> must be dropped across the barrier; backends absorbing the barrier
> take LogicalDecodingControlLock in shared mode (via
> IsXLogLogicalInfoEnabled()), so holding it across WaitForProcSignalBarrier()
> would deadlock.
>
> So if two backends create the first logical slot(s) at the same time,
> both can pass the initial check while the flag is still false, and both
> end up writing a status-change record.  The second (redundant) record
> lands after the decoding start point the other slot already reserved,
> so that slot scans it and trips the elog() above.
>
> REPACK CONCURRENTLY makes this easy to hit because each operation
> creates a temporary logical slot (max_repack_replication_slots), so firing
> many REPACKs in parallel from the disabled state gives you many backends
> racing to perform the very first activation.  But nothing here is REPACK-specific.
>
> To reproduce this i have added a test using logical-decoding-activation
> injection point in 051_effective_wal_level.pl
>
> I also hit it with a stress script [1] which was again related to the
> BUG #19519, instead of vacuum full i replaced it with REPACK (concurrently).
>
> To fix this I re-checked the flag after re-acquiring the lock and skipped
> the state change/WAL write if another backend had already completed
> the transition.
>
>     LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
>
>     if (LogicalDecodingCtl->logical_decoding_enabled)
>     {
>         LogicalDecodingCtl->pending_disable = false;
>         LWLockRelease(LogicalDecodingControlLock);
>         return;
>     }
>
>     START_CRIT_SECTION();
>
> With this, only the backend that actually performs the disabled->enabled
> transition writes a record, and every slot's start point stays at or after
> it, restoring the case xlog_decode() depends on.
>
> Patch attached.  It fixes logicalctl.c and adds a regression test to
> 051_effective_wal_level.pl reusing the existing injection-point
> infrastructure.  With the fix the test passes; without it it fails with
> the exact error above.

Thank you for the report and the patch!

I agree with your analysis and the patch basically looks good to me.
Here are some review comments:

+ # Let the released backend finish creating its slot: feed running-xacts
+ # records until it reaches a consistent point (poll_query_until re-runs the
+ # query, so pg_log_standby_snapshot() is called until the slot is created).
+ $primary->poll_query_until(
+ 'postgres', qq[
+select (pg_log_standby_snapshot() is not null)
+  and exists (select 1 from pg_replication_slots
+              where slot_name = 'slot_stray' and confirmed_flush_lsn
is not null)
+]);

I don't think we need to call pg_log_standby_snapshot() until the slot
is created since the slot creation writes the running-xacts record
during the slot creation.

---
+ # Decoding the first slot must not stumble over a stray status-change record.
+ my ($decode_rc, $decode_out, $decode_err) = $primary->psql(
+ 'postgres',
+ qq[select count(*) from pg_logical_slot_get_changes('slot_first',
null, null)],
+ on_error_die => 0);
+ is($decode_rc, 0, "decoding a concurrently-created slot succeeds");
+ unlike(
+ $decode_err,
+ qr/unexpected logical decoding status change/,
+ "no redundant status-change record was decoded");

We can use safe_psql() to check if the query successfully completes.

I've made some cosmetic changes to the comment and the new test
including the above comments. Please review it.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments:

v2-0001-Fix-race-condition-when-enabling-logical-decoding.patch (application/x-patch, 6.0K) download From 94979530b57adc2a68f48109fffcb30339da5ff0 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Tue, 14 Jul 2026 12:22:24 -0700 Subject: [PATCH v2] Fix race condition when enabling logical decoding concurrently. With wal_level = 'replica', logical decoding is enabled on demand when the first logical replication slot is created: When enabling logical decoding, EnableLogicalDecoding() flips the shared logical_decoding_enabled flag and writes an XLOG_LOGICAL_DECODING_STATUS_CHANGE record so that standbys follow the status change. The initial "already enabled?" check and the WAL record write happen under two separate acquisitions of LogicalDecodingControlLock, since the lock must be released while waiting for the ProcSignalBarrier: processes absorbing the barrier acquire the same lock in shared mode. Consequently, if two backends concurrently created the first logical slots, both could pass the initial check and both write a status-change record. The redundant record lands after the decoding start point already reserved by the other backend's slot, so decoding that slot processes the record and fails with "unexpected logical decoding status change", as xlog_decode() assumes that no such record can appear within the WAL range any slot decodes. Fix by re-checking the status after re-acquiring the lock, so that only the backend that actually performs the disabled->enabled transition writes the WAL record. Reported-by: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Author: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Discussion: https://postgr.es/m/CAFC+b6oYzmAgp7F0ivrhfZT46-CjvCTrU9pWuMNcem-52YjOTw@mail.gmail.com Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 11 ++++ .../recovery/t/051_effective_wal_level.pl | 61 ++++++++++++++++++- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index c11d1316450..7074900514a 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -384,6 +384,17 @@ EnableLogicalDecoding(void) LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Re-check whether logical decoding got enabled while we waited for the + * barrier above. + */ + if (LogicalDecodingCtl->logical_decoding_enabled) + { + LogicalDecodingCtl->pending_disable = false; + LWLockRelease(LogicalDecodingControlLock); + return; + } + START_CRIT_SECTION(); /* diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index d4bc7f0aa40..2cf2ea6546d 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -326,11 +326,12 @@ $standby3->safe_psql('postgres', $standby3->stop; -# Test the race condition at end of the recovery between the startup and logical -# decoding status change. This test requires injection points enabled. if ( $ENV{enable_injection_points} eq 'yes' && $primary->check_extension('injection_points')) { + # Test the race condition at end of the recovery between the startup and logical + # decoding status change. This test requires injection points enabled. + # Initialize standby4 and start it. my $standby4 = PostgreSQL::Test::Cluster->new('standby4'); $standby4->init_from_backup($primary, 'my_backup', has_streaming => 1); @@ -381,9 +382,63 @@ if ( $ENV{enable_injection_points} eq 'yes' test_wal_level($primary, "replica|replica", "effective_wal_level got decreased to 'replica' on primary"); + # Test that concurrent activations don't write redundant status-change records. + + # Start a psql session and stop it in the middle of the activation process. + my $psql_create_slot = $primary->background_psql('postgres'); + $psql_create_slot->query_until( + qr/create_slot_1/, + q(\echo create_slot_1 +select injection_points_set_local(); +select injection_points_attach('logical-decoding-activation', 'wait'); +select pg_create_logical_replication_slot('slot_1', 'test_decoding'); +)); + $primary->wait_for_event('client backend', 'logical-decoding-activation'); + note("injection_point 'logical-decoding-activation' is reached"); + + # A second backend concurrently enables logical decoding and finishes creating + # its slot, writing the status-change record. The slot reserves its decoding + # start point after its own status-change record. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('slot_2', 'test_decoding')] + ); + test_wal_level($primary, "replica|logical", + "logical decoding enabled by the first of two concurrent activations" + ); + + # Resume the first backend to complete the slot creation. It must not write + # a second redundant status-change record as logical decoding is already + # enabled. + $primary->safe_psql('postgres', + qq[select injection_points_wakeup('logical-decoding-activation')]); + + # Let the released backend finish creating its slot. + $psql_create_slot->quit; + + # Decode from slot_2, whose start point precedes where a redundant + # status-change record would have been written; this fails in xlog_decode() + # if one exists. + is( $primary->safe_psql( + 'postgres', + qq[SELECT count(*) FROM pg_logical_slot_get_changes('slot_2', NULL, NULL, 'skip-empty-xacts', '1')] + ), + 0, + 'decoding a concurrently-created slot succeeds'); + + # Restore the disabled state for the tests that follow. + $primary->safe_psql( + 'postgres', + qq[ +select pg_drop_replication_slot('slot_1'); +select pg_drop_replication_slot('slot_2'); +]); + wait_for_logical_decoding_disabled($primary); + + # Test a race when logical decoding activation is concurrently interrupted. + # Start a psql session to test the case where the activation process is # interrupted. - my $psql_create_slot = $primary->background_psql('postgres'); + $psql_create_slot = $primary->background_psql('postgres'); # Start the logical decoding activation process upon creating the logical # slot, but it will wait due to the injection point. -- 2.54.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-16 01:21  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 4 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-16 01:21 UTC (permalink / raw)
  To: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: pgsql-hackers

On Tue, Jul 14, 2026 at 2:02 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Thu, Jul 9, 2026 at 9:23 PM Srinath Reddy Sadipiralla
> <srinath2133@gmail.com> wrote:
> >
> >
> >
> > ---------- Forwarded message ---------
> > From: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
> > Date: Fri, Jul 10, 2026 at 9:48 AM
> > Subject: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
> > To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>
> > Cc: Masahiko Sawada <sawada.mshk@gmail.com>
> >
> >
> > Hi,
> >
> > While stress-testing REPACK CONCURRENTLY, I was in that
> > area looking at BUG #19519 (REPACK failing with "missingchunk
> > number N for toast value" [0]; note that one reproduces with plain
> > REPACK too, since it's the shared copy_table_data() path, so
> > it's independent of what follows), I hit a different, reproducible
> > failure under high concurrency:
> >     ERROR:  unexpected logical decoding status change 1
> >
> > I believe this is a race bug in the on-demand logical decoding
> > activation machinery (logicalctl.c), exposed by
> > REPACK CONCURRENTLY but not actually specific to it, as
> > this can be reproduced using pg_create_logical_replication_slot and CREATE_REPLICATION_SLOT.
> >
> > At wal_level = 'replica', logical decoding is toggled on the first time a
> > logical slot is created.  EnableLogicalDecoding() sets the shared
> > logical_decoding_enabled flag and writes an
> > XLOG_LOGICAL_DECODING_STATUS_CHANGE record so standbys
> > learn about the change.  On the decoding side, xlog_decode() treats
> > that record as unreachable:
> > elog(ERROR, "unexpected logical decoding status change %d", ...);
> >
> > The reasoning (per the comment there) is that no running decoder can ever
> > have such a record within the LSN range it scans: there is exactly one
> > enable record per disabled->enabled transition, and it precedes the
> > decoding start point reserved by any slot.
> >
> > That case does not hold under concurrency.  EnableLogicalDecoding()
> > does:
> >
> >     LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
> >     if (logical_decoding_enabled)     /* already on? -> done */
> >         { ... return; }
> >     LWLockRelease(...);
> >
> >     WaitForProcSignalBarrier(...);    /* lock released here */
> >
> >     LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
> >     logical_decoding_enabled = true;
> >     write_logical_decoding_status_update_record(true);   /* the record */
> >     LWLockRelease(...);
> >
> > The "already enabled?" check and the record write happen under two
> > separate lock acquisitions, with the barrier wait in between.  The lock
> > must be dropped across the barrier; backends absorbing the barrier
> > take LogicalDecodingControlLock in shared mode (via
> > IsXLogLogicalInfoEnabled()), so holding it across WaitForProcSignalBarrier()
> > would deadlock.
> >
> > So if two backends create the first logical slot(s) at the same time,
> > both can pass the initial check while the flag is still false, and both
> > end up writing a status-change record.  The second (redundant) record
> > lands after the decoding start point the other slot already reserved,
> > so that slot scans it and trips the elog() above.
> >
> > REPACK CONCURRENTLY makes this easy to hit because each operation
> > creates a temporary logical slot (max_repack_replication_slots), so firing
> > many REPACKs in parallel from the disabled state gives you many backends
> > racing to perform the very first activation.  But nothing here is REPACK-specific.
> >
> > To reproduce this i have added a test using logical-decoding-activation
> > injection point in 051_effective_wal_level.pl
> >
> > I also hit it with a stress script [1] which was again related to the
> > BUG #19519, instead of vacuum full i replaced it with REPACK (concurrently).
> >
> > To fix this I re-checked the flag after re-acquiring the lock and skipped
> > the state change/WAL write if another backend had already completed
> > the transition.
> >
> >     LWLockAcquire(LogicalDecodingControlLock, EXCLUSIVE);
> >
> >     if (LogicalDecodingCtl->logical_decoding_enabled)
> >     {
> >         LogicalDecodingCtl->pending_disable = false;
> >         LWLockRelease(LogicalDecodingControlLock);
> >         return;
> >     }
> >
> >     START_CRIT_SECTION();
> >
> > With this, only the backend that actually performs the disabled->enabled
> > transition writes a record, and every slot's start point stays at or after
> > it, restoring the case xlog_decode() depends on.
> >
> > Patch attached.  It fixes logicalctl.c and adds a regression test to
> > 051_effective_wal_level.pl reusing the existing injection-point
> > infrastructure.  With the fix the test passes; without it it fails with
> > the exact error above.
>
> Thank you for the report and the patch!
>
> I agree with your analysis and the patch basically looks good to me.
> Here are some review comments:
>
> + # Let the released backend finish creating its slot: feed running-xacts
> + # records until it reaches a consistent point (poll_query_until re-runs the
> + # query, so pg_log_standby_snapshot() is called until the slot is created).
> + $primary->poll_query_until(
> + 'postgres', qq[
> +select (pg_log_standby_snapshot() is not null)
> +  and exists (select 1 from pg_replication_slots
> +              where slot_name = 'slot_stray' and confirmed_flush_lsn
> is not null)
> +]);
>
> I don't think we need to call pg_log_standby_snapshot() until the slot
> is created since the slot creation writes the running-xacts record
> during the slot creation.
>
> ---
> + # Decoding the first slot must not stumble over a stray status-change record.
> + my ($decode_rc, $decode_out, $decode_err) = $primary->psql(
> + 'postgres',
> + qq[select count(*) from pg_logical_slot_get_changes('slot_first',
> null, null)],
> + on_error_die => 0);
> + is($decode_rc, 0, "decoding a concurrently-created slot succeeds");
> + unlike(
> + $decode_err,
> + qr/unexpected logical decoding status change/,
> + "no redundant status-change record was decoded");
>
> We can use safe_psql() to check if the query successfully completes.
>
> I've made some cosmetic changes to the comment and the new test
> including the above comments. Please review it.

While reviewing concurrency aspects of this code before pushing the
fix, I found other race conditions in the same area: logical decoding
can be deactivated while a logical slot is being created on a standby.

On standbys, logical decoding can be deactivated while a logical slot
is being created: either by replaying an
XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by the end-of-recovery
transition upon promotion, which deactivates logical decoding if no
valid logical slot exists. When logical decoding is deactivated, all
logical slots on the standby are invalidated, but this cannot find a
slot that is not visible yet. Therefore, a slot creation whose status
check interleaved with the deactivation could continue based on a
stale status. This affects two paths:

For regular slot creation, EnsureLogicalDecodingEnabled() assumed that
logical decoding must still be enabled during recovery since the
caller had already checked it. If a promotion interleaves as described
 above, the backend creating the slot fails with:

    TRAP: failed Assert("IsLogicalDecodingEnabled()"), File: "logicalctl.c"

For slot synchronization, the local slot could be created and
persisted based on the remote slot information fetched before the
deactivation was replayed, leaving a valid slot whose restart_lsn
precedes the deactivation. Decoding such a slot after a failover fails
 with:

    ERROR:  unexpected logical decoding status change 0

These races are confined to the narrow window between checking the
logical decoding status and the new slot becoming visible; once the
slot is visible, the invalidation performed by the deactivation
already covers it. So the fix is simple: re-check the logical decoding
status after the new slot becomes visible. Regular slot creation
raises an error and slot synchronization skips persisting the slot. If
the deactivation happens after the recheck instead, it is guaranteed
to invalidate the now-visible slot as usual. The attached 0002
implements this.

0001 is the fix for the originally reported issue, unchanged from the
previous version.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments: download all (2 files, .tar.gz)

v3-0002-Fix-races-between-deactivation-of-logical-decodin.patch (text/x-patch, 16.6K) download From 548ebc5f8b52ef8fd3f0eec652fad55c4653965f Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Wed, 15 Jul 2026 11:49:28 -0700 Subject: [PATCH v3 2/2] Fix races between deactivation of logical decoding and slot creation. On standbys, logical decoding can be deactivated while a logical slot is being created: either by replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by the end-of-recovery transition upon promotion, which deactivates logical decoding if no valid logical slot exists. Both could interleave with a check of the logical decoding status performed before the new slot becomes visible, because the slot invalidation executed as part of the deactivation cannot find a slot that is not visible yet. For regular slot creation on standbys, EnsureLogicalDecodingEnabled() assumed that logical decoding must still be enabled during recovery since the caller had already checked it, tripping an assertion failure if a concurrent deactivation interleaved. For slot synchronization, the local slot could be created and persisted based on the remote slot information fetched before the deactivation was replayed, leaving a valid slot whose restart_lsn precedes the deactivation. Fix both paths by re-checking the logical decoding status after the new slot becomes visible: regular slot creation raises an error, and slot synchronization skips persisting the slot. If the deactivation happens after the re-check instead, it is guaranteed to invalidate the now-visible slot. Discussion: https://postgr.es/m/ Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 38 +++-- src/backend/replication/logical/slotsync.c | 37 ++++ src/backend/replication/slot.c | 2 + src/backend/replication/slotfuncs.c | 13 +- src/backend/replication/walsender.c | 4 +- .../recovery/t/051_effective_wal_level.pl | 158 ++++++++++++++++++ 6 files changed, 237 insertions(+), 15 deletions(-) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 7074900514a..0a70af93bb5 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -274,11 +274,10 @@ abort_logical_decoding_activation(int code, Datum arg) /* * Enable logical decoding if disabled. * - * If this function is called during recovery, it simply returns without - * action since the logical decoding status change is not allowed during - * this time. The logical decoding status depends on the status on the primary. - * The caller should use CheckLogicalDecodingRequirements() before calling this - * function to make sure that the logical decoding status can be modified. + * If this function is called during recovery, it just checks that logical + * decoding is still enabled, since the logical decoding status cannot be + * changed during this time. The logical decoding status depends on the + * status on the primary. * * Note that there is no interlock between logical decoding activation * and slot creation. To ensure enabling logical decoding, the caller @@ -298,11 +297,19 @@ EnsureLogicalDecodingEnabled(void) if (RecoveryInProgress()) { /* - * CheckLogicalDecodingRequirements() must have already errored out if - * logical decoding is not enabled since we cannot enable the logical - * decoding status during recovery. + * The caller has already checked that logical decoding is enabled via + * CheckLogicalDecodingRequirements(), but the status could have been + * disabled concurrently before our slot being created: either by + * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by + * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We + * cannot enable logical decoding during recovery, so raise an error. */ - Assert(IsLogicalDecodingEnabled()); + if (!IsLogicalDecodingEnabled()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("logical decoding on standby requires \"effective_wal_level\" >= \"logical\" on the primary"), + errdetail("Logical decoding was concurrently disabled during the logical replication slot creation."))); + return; } @@ -604,10 +611,15 @@ UpdateLogicalDecodingStatusEndOfRecovery(void) * already occur due to the checkpointer's asynchronous deactivation * process. * - * For 'disable' case, backend cannot create logical replication slots - * during recovery (see checks in CheckLogicalDecodingRequirements()), - * which prevents a race condition between disabling logical decoding and - * concurrent slot creation. + * For 'disable' case, a backend concurrently creating a logical slot on a + * standby could have passed its CheckLogicalDecodingRequirements() check + * while making its slot visible only after our slot check above. Such a + * backend rechecks the status after creating the slot in + * EnsureLogicalDecodingEnabled() and raises an error if logical decoding + * has been disabled meanwhile, so it cannot end up with a logical slot + * while logical decoding remains disabled. (If recovery has already ended + * by the time of the recheck, the backend instead enables logical + * decoding by itself, which is fine after promotion.) */ if (new_status != LogicalDecodingCtl->logical_decoding_enabled) { diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index d1936823506..e52c22f0c24 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -67,6 +67,7 @@ #include "pgstat.h" #include "postmaster/interrupt.h" #include "replication/logical.h" +#include "replication/logicalctl.h" #include "replication/slotsync.h" #include "replication/snapbuild.h" #include "storage/ipc.h" @@ -717,6 +718,42 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } + /* + * Do not persist the slot if logical decoding got disabled concurrently. + * This can happen if the last logical slot on the primary was dropped + * and the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was + * replayed after we fetched the remote slot information: WAL records + * following the slot's restart_lsn might lack the information required + * by logical decoding, and the slot invalidation performed when + * replaying the record could not find our slot as it was not visible + * yet. + * + * It is important to perform this check after the slot became visible + * and before persisting it. This way, even if the status change record + * is replayed after this check, the replay will invalidate our slot. + * + * If the check fails, we keep the temporary slot and let the caller + * retry; the next cycle fetches the remote slot information again and + * will drop this slot as the remote slot no longer exists. + * + * XXX: this check cannot detect the case where logical decoding is + * already re-enabled by a slot creation on the primary at this point. + * Detecting that would require comparing the slot's restart_lsn with + * the LSN at which logical decoding was last enabled. + */ + if (!IsLogicalDecodingEnabled()) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding was concurrently disabled.")); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + ReplicationSlotPersist(); ereport(LOG, diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c index c7ab82a28e1..1a0ff682068 100644 --- a/src/backend/replication/slot.c +++ b/src/backend/replication/slot.c @@ -420,6 +420,8 @@ ReplicationSlotCreate(const char *name, bool db_specific, errmsg("cannot enable failover for a temporary replication slot")); } + INJECTION_POINT("replication-slot-create-begin", NULL); + /* * If some other backend ran this code concurrently with us, we'd likely * both allocate the same slot, and that would be bad. We'd also be at diff --git a/src/backend/replication/slotfuncs.c b/src/backend/replication/slotfuncs.c index 16fbd383735..813180fece7 100644 --- a/src/backend/replication/slotfuncs.c +++ b/src/backend/replication/slotfuncs.c @@ -153,7 +153,18 @@ create_logical_replication_slot(char *name, char *plugin, * decoding context. */ EnsureLogicalDecodingEnabled(); - Assert(IsLogicalDecodingEnabled()); + + /* + * Outside of recovery, holding a valid logical slot prevents logical + * decoding from being disabled. During recovery, however, replaying a + * status change record can disable it at any time regardless of slot + * existence, so we cannot assert that it is still enabled here. That is + * harmless: such a replay invalidates our already-visible slot, so this + * slot creation fails afterwards (by a recovery conflict or the + * requirement re-check in CreateInitDecodingContext()) instead of leaving + * a usable slot behind. + */ + Assert(RecoveryInProgress() || IsLogicalDecodingEnabled()); /* * Create logical decoding context to find start point or, if we don't diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c index 35ebc7e61c8..c65dd324325 100644 --- a/src/backend/replication/walsender.c +++ b/src/backend/replication/walsender.c @@ -1372,7 +1372,9 @@ CreateReplicationSlot(CreateReplicationSlotCmd *cmd) * logical decoding context. */ EnsureLogicalDecodingEnabled(); - Assert(IsLogicalDecodingEnabled()); + + /* See the comment in create_logical_replication_slot() */ + Assert(RecoveryInProgress() || IsLogicalDecodingEnabled()); ctx = CreateInitDecodingContext(cmd->plugin, NIL, need_full_snapshot, false, diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 2cf2ea6546d..a685c2cdcd9 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -507,6 +507,164 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled test_wal_level($primary, "replica|logical", "effective_wal_level remains 'logical' even after the concurrent activation is interrupted" ); + + # 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 their slot becomes visible 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. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot2')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql( + 'postgres', qq[ +alter system set autovacuum = off; +select pg_reload_conf(); +]); + + # Initialize standby5 node, setting up the requirements for slot + # synchronization. + $primary->safe_psql('postgres', + qq[select pg_create_physical_replication_slot('phys_slot')]); + my $standby5 = PostgreSQL::Test::Cluster->new('standby5'); + $standby5->init_from_backup($primary, 'my_backup', has_streaming => 1); + my $connstr = $primary->connstr; + $standby5->append_conf( + 'postgresql.conf', qq[ +primary_slot_name = 'phys_slot' +primary_conninfo = '$connstr dbname=postgres' +hot_standby_feedback = on +]); + $standby5->start; + + # Test that slot synchronization doesn't persist a slot whose remote + # slot information was fetched before a deactivation was replayed. + # Otherwise, the slot would survive with a restart_lsn preceding the + # deactivation, as the slot invalidation performed by the replay cannot + # find the slot that is not visible yet. + + # Enable logical decoding by creating a failover-enabled slot, and wait + # for the standby to replay the activation. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5"); + + # Start slot synchronization, stopping it after fetching the remote slot + # information but before creating the local slot. + my $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); + + # Drop the last logical slot on the primary and wait for the standby to + # replay the deactivation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|replica", + "logical decoding got deactivated on standby5"); + + # Resume the slot synchronization; it must skip persisting the slot. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('replication-slot-create-begin')]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot"/, $log_offset); + $psql_sync_slot->quit; + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5"); + + # Test that logical slot creation on a standby fails cleanly if logical + # decoding is concurrently deactivated by the end-of-recovery transition + # upon promotion, which cannot find the slot that is not visible yet. + + # Enable logical decoding again. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('test_slot3', 'test_decoding')] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated again on standby5"); + + # Hold the startup process right after the end-of-recovery status + # change, before recovery actually ends. + $standby5->safe_psql('postgres', + qq[select injection_points_attach('startup-logical-decoding-status-change-end-of-recovery', 'wait')] + ); + + # Start creating a logical slot, stopping it before the slot becomes + # visible. + $psql_create_slot = + $standby5->background_psql('postgres', on_error_stop => 0); + $psql_create_slot->query_until( + qr/create_standby5_slot/, + q(\echo create_standby5_slot +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_create_logical_replication_slot('standby5_slot', 'test_decoding'); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); + + # Promote the standby without waiting; the startup process deactivates + # logical decoding as no logical slot is visible, and stops at the + # injection point, still in recovery. + $standby5->safe_psql('postgres', qq[select pg_promote(false)]); + $standby5->wait_for_event('startup', + 'startup-logical-decoding-status-change-end-of-recovery'); + + # Resume the slot creation; it must fail cleanly. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('replication-slot-create-begin')]); + $standby5->wait_for_log( + qr/ERROR: .* logical decoding on standby requires "effective_wal_level" >= "logical" on the primary/, + $log_offset); + $psql_create_slot->quit; + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no slot is left behind on standby5"); + + # Let the promotion complete. + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('startup-logical-decoding-status-change-end-of-recovery')] + ); + $standby5->safe_psql('postgres', + qq[select injection_points_detach('startup-logical-decoding-status-change-end-of-recovery')] + ); + $standby5->poll_query_until('postgres', + qq[select not pg_is_in_recovery()]) + or die "timed out waiting for promotion"; + + # Retrying the slot creation on the promoted standby5 must succeed and + # activate logical decoding. + $standby5->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('standby5_slot', 'test_decoding')] + ); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on the promoted standby5 after retry" + ); } $primary->stop; -- 2.54.0
v3-0001-Fix-race-condition-when-enabling-logical-decoding.patch (text/x-patch, 6.0K) download From c3201621a6f9e067ba35e51f1ec5a91624907967 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Tue, 14 Jul 2026 12:22:24 -0700 Subject: [PATCH v3 1/2] Fix race condition when enabling logical decoding concurrently. With wal_level = 'replica', logical decoding is enabled on demand when the first logical replication slot is created: When enabling logical decoding, EnableLogicalDecoding() flips the shared logical_decoding_enabled flag and writes an XLOG_LOGICAL_DECODING_STATUS_CHANGE record so that standbys follow the status change. The initial "already enabled?" check and the WAL record write happen under two separate acquisitions of LogicalDecodingControlLock, since the lock must be released while waiting for the ProcSignalBarrier: processes absorbing the barrier acquire the same lock in shared mode. Consequently, if two backends concurrently created the first logical slots, both could pass the initial check and both write a status-change record. The redundant record lands after the decoding start point already reserved by the other backend's slot, so decoding that slot processes the record and fails with "unexpected logical decoding status change", as xlog_decode() assumes that no such record can appear within the WAL range any slot decodes. Fix by re-checking the status after re-acquiring the lock, so that only the backend that actually performs the disabled->enabled transition writes the WAL record. Reported-by: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Author: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Discussion: https://postgr.es/m/CAFC+b6oYzmAgp7F0ivrhfZT46-CjvCTrU9pWuMNcem-52YjOTw@mail.gmail.com Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 11 ++++ .../recovery/t/051_effective_wal_level.pl | 61 ++++++++++++++++++- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index c11d1316450..7074900514a 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -384,6 +384,17 @@ EnableLogicalDecoding(void) LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Re-check whether logical decoding got enabled while we waited for the + * barrier above. + */ + if (LogicalDecodingCtl->logical_decoding_enabled) + { + LogicalDecodingCtl->pending_disable = false; + LWLockRelease(LogicalDecodingControlLock); + return; + } + START_CRIT_SECTION(); /* diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index d4bc7f0aa40..2cf2ea6546d 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -326,11 +326,12 @@ $standby3->safe_psql('postgres', $standby3->stop; -# Test the race condition at end of the recovery between the startup and logical -# decoding status change. This test requires injection points enabled. if ( $ENV{enable_injection_points} eq 'yes' && $primary->check_extension('injection_points')) { + # Test the race condition at end of the recovery between the startup and logical + # decoding status change. This test requires injection points enabled. + # Initialize standby4 and start it. my $standby4 = PostgreSQL::Test::Cluster->new('standby4'); $standby4->init_from_backup($primary, 'my_backup', has_streaming => 1); @@ -381,9 +382,63 @@ if ( $ENV{enable_injection_points} eq 'yes' test_wal_level($primary, "replica|replica", "effective_wal_level got decreased to 'replica' on primary"); + # Test that concurrent activations don't write redundant status-change records. + + # Start a psql session and stop it in the middle of the activation process. + my $psql_create_slot = $primary->background_psql('postgres'); + $psql_create_slot->query_until( + qr/create_slot_1/, + q(\echo create_slot_1 +select injection_points_set_local(); +select injection_points_attach('logical-decoding-activation', 'wait'); +select pg_create_logical_replication_slot('slot_1', 'test_decoding'); +)); + $primary->wait_for_event('client backend', 'logical-decoding-activation'); + note("injection_point 'logical-decoding-activation' is reached"); + + # A second backend concurrently enables logical decoding and finishes creating + # its slot, writing the status-change record. The slot reserves its decoding + # start point after its own status-change record. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('slot_2', 'test_decoding')] + ); + test_wal_level($primary, "replica|logical", + "logical decoding enabled by the first of two concurrent activations" + ); + + # Resume the first backend to complete the slot creation. It must not write + # a second redundant status-change record as logical decoding is already + # enabled. + $primary->safe_psql('postgres', + qq[select injection_points_wakeup('logical-decoding-activation')]); + + # Let the released backend finish creating its slot. + $psql_create_slot->quit; + + # Decode from slot_2, whose start point precedes where a redundant + # status-change record would have been written; this fails in xlog_decode() + # if one exists. + is( $primary->safe_psql( + 'postgres', + qq[SELECT count(*) FROM pg_logical_slot_get_changes('slot_2', NULL, NULL, 'skip-empty-xacts', '1')] + ), + 0, + 'decoding a concurrently-created slot succeeds'); + + # Restore the disabled state for the tests that follow. + $primary->safe_psql( + 'postgres', + qq[ +select pg_drop_replication_slot('slot_1'); +select pg_drop_replication_slot('slot_2'); +]); + wait_for_logical_decoding_disabled($primary); + + # Test a race when logical decoding activation is concurrently interrupted. + # Start a psql session to test the case where the activation process is # interrupted. - my $psql_create_slot = $primary->background_psql('postgres'); + $psql_create_slot = $primary->background_psql('postgres'); # Start the logical decoding activation process upon creating the logical # slot, but it will wait due to the injection point. -- 2.54.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-16 05:06  Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 0 replies; 59+ messages in thread

From: Srinath Reddy Sadipiralla @ 2026-07-16 05:06 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: pgsql-hackers

Hi Masahiko-San,

On Wed, Jul 15, 2026 at 2:33 AM Masahiko Sawada <sawada.mshk@gmail.com>
wrote:

>
> + # Let the released backend finish creating its slot: feed running-xacts
> + # records until it reaches a consistent point (poll_query_until re-runs
> the
> + # query, so pg_log_standby_snapshot() is called until the slot is
> created).
> + $primary->poll_query_until(
> + 'postgres', qq[
> +select (pg_log_standby_snapshot() is not null)
> +  and exists (select 1 from pg_replication_slots
> +              where slot_name = 'slot_stray' and confirmed_flush_lsn
> is not null)
> +]);
>
> I don't think we need to call pg_log_standby_snapshot() until the slot
> is created since the slot creation writes the running-xacts record
> during the slot creation.
>
> ---
> + # Decoding the first slot must not stumble over a stray status-change
> record.
> + my ($decode_rc, $decode_out, $decode_err) = $primary->psql(
> + 'postgres',
> + qq[select count(*) from pg_logical_slot_get_changes('slot_first',
> null, null)],
> + on_error_die => 0);
> + is($decode_rc, 0, "decoding a concurrently-created slot succeeds");
> + unlike(
> + $decode_err,
> + qr/unexpected logical decoding status change/,
> + "no redundant status-change record was decoded");
>
> We can use safe_psql() to check if the query successfully completes.
>
>
makes sense.


> I've made some cosmetic changes to the comment and the new test
> including the above comments. Please review it.
>

LGTM.

-- 
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/

^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-20 16:47  Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 1 reply; 59+ messages in thread

From: Srinath Reddy Sadipiralla @ 2026-07-20 16:47 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: pgsql-hackers

Hi Masahiko-san,

On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada <sawada.mshk@gmail.com>
wrote:

>
> While reviewing concurrency aspects of this code before pushing the
> fix, I found other race conditions in the same area: logical decoding
> can be deactivated while a logical slot is being created on a standby.
>
> On standbys, logical decoding can be deactivated while a logical slot
> is being created: either by replaying an
> XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by the end-of-recovery
> transition upon promotion, which deactivates logical decoding if no
> valid logical slot exists. When logical decoding is deactivated, all
> logical slots on the standby are invalidated, but this cannot find a
> slot that is not visible yet. Therefore, a slot creation whose status
> check interleaved with the deactivation could continue based on a
> stale status. This affects two paths:
>
> For regular slot creation, EnsureLogicalDecodingEnabled() assumed that
> logical decoding must still be enabled during recovery since the
> caller had already checked it. If a promotion interleaves as described
>  above, the backend creating the slot fails with:
>
>     TRAP: failed Assert("IsLogicalDecodingEnabled()"), File: "logicalctl.c"
>
> For slot synchronization, the local slot could be created and
> persisted based on the remote slot information fetched before the
> deactivation was replayed, leaving a valid slot whose restart_lsn
> precedes the deactivation. Decoding such a slot after a failover fails
>  with:
>
>     ERROR:  unexpected logical decoding status change 0
>
> These races are confined to the narrow window between checking the
> logical decoding status and the new slot becoming visible; once the
> slot is visible, the invalidation performed by the deactivation
> already covers it. So the fix is simple: re-check the logical decoding
> status after the new slot becomes visible. Regular slot creation
> raises an error and slot synchronization skips persisting the slot. If
> the deactivation happens after the recheck instead, it is guaranteed
> to invalidate the now-visible slot as usual. The attached 0002
> implements this.
>

i have looked into these conditions and they make sense and reviewed the
v3-0002 patch, LGTM.

while reviewing this, I had a thought (it's not related to these race
issues), but
if we disable logical decoding in primary by removing all the slots when
wal_level = replica; it directly invalidates the private slots of the
standby which
seems unfair cause there might be some consumers using it, but then suddenly
they get an error to either change the wal_level = logical on primary or
add a slot
on the primary, but instead i think we can make primary aware of the private
slots of standby and keep logical decoding on, during the
XLOG_LOGICAL_DECODING_STATUS_CHANGE record redo, thoughts?


-- 
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/
"The truth is... I am Iron Man."

^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-21 00:42  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-21 00:42 UTC (permalink / raw)
  To: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: pgsql-hackers

On Mon, Jul 20, 2026 at 9:47 AM Srinath Reddy Sadipiralla
<srinath2133@gmail.com> wrote:
>
> Hi Masahiko-san,
>
> On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>>
>>
>> While reviewing concurrency aspects of this code before pushing the
>> fix, I found other race conditions in the same area: logical decoding
>> can be deactivated while a logical slot is being created on a standby.
>>
>> On standbys, logical decoding can be deactivated while a logical slot
>> is being created: either by replaying an
>> XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by the end-of-recovery
>> transition upon promotion, which deactivates logical decoding if no
>> valid logical slot exists. When logical decoding is deactivated, all
>> logical slots on the standby are invalidated, but this cannot find a
>> slot that is not visible yet. Therefore, a slot creation whose status
>> check interleaved with the deactivation could continue based on a
>> stale status. This affects two paths:
>>
>> For regular slot creation, EnsureLogicalDecodingEnabled() assumed that
>> logical decoding must still be enabled during recovery since the
>> caller had already checked it. If a promotion interleaves as described
>>  above, the backend creating the slot fails with:
>>
>>     TRAP: failed Assert("IsLogicalDecodingEnabled()"), File: "logicalctl.c"
>>
>> For slot synchronization, the local slot could be created and
>> persisted based on the remote slot information fetched before the
>> deactivation was replayed, leaving a valid slot whose restart_lsn
>> precedes the deactivation. Decoding such a slot after a failover fails
>>  with:
>>
>>     ERROR:  unexpected logical decoding status change 0
>>
>> These races are confined to the narrow window between checking the
>> logical decoding status and the new slot becoming visible; once the
>> slot is visible, the invalidation performed by the deactivation
>> already covers it. So the fix is simple: re-check the logical decoding
>> status after the new slot becomes visible. Regular slot creation
>> raises an error and slot synchronization skips persisting the slot. If
>> the deactivation happens after the recheck instead, it is guaranteed
>> to invalidate the now-visible slot as usual. The attached 0002
>> implements this.
>
>
> i have looked into these conditions and they make sense and reviewed the
> v3-0002 patch, LGTM.

Thank you for reviewing the patch!

>
> while reviewing this, I had a thought (it's not related to these race issues), but
> if we disable logical decoding in primary by removing all the slots when
> wal_level = replica; it directly invalidates the private slots of the standby which
> seems unfair cause there might be some consumers using it, but then suddenly
> they get an error to either change the wal_level = logical on primary or add a slot
> on the primary, but instead i think we can make primary aware of the private
> slots of standby and keep logical decoding on, during the
> XLOG_LOGICAL_DECODING_STATUS_CHANGE record redo, thoughts?
>

IIUC it's too late to inform the primary during
XLOG_LOGICAL_DECODING_STATUS_CHANGE redo; the standby replays that
record only after the primary has disabled logical decoding, so WAL
lacking the information required for logical decoding has already been
generated. Once such a gap exists, the standby's slots cannot decode
past it even if the primary re-enabled logical decoding in response,
so we would have to invalidate them anyway.

Alternatively, standbys could proactively tell the primary about their
slots (like hot_standby_feedback), but I don't think this can be made
reliable. With cascaded standbys the information has to be propagated
up through each level, and the propagation lag leaves an unavoidable
race: by the time the primary learns that a downstream server still
needs logical WAL, its slots may already be gone, or a new slot could
be created right after the primary decided to disable.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-21 04:52  Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 0 replies; 59+ messages in thread

From: Srinath Reddy Sadipiralla @ 2026-07-21 04:52 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: pgsql-hackers

On Tue, Jul 21, 2026 at 6:12 AM Masahiko Sawada <sawada.mshk@gmail.com>
wrote:

>
> IIUC it's too late to inform the primary during
> XLOG_LOGICAL_DECODING_STATUS_CHANGE redo; the standby replays that
> record only after the primary has disabled logical decoding, so WAL
> lacking the information required for logical decoding has already been
> generated. Once such a gap exists, the standby's slots cannot decode
> past it even if the primary re-enabled logical decoding in response,
> so we would have to invalidate them anyway.
>
> Alternatively, standbys could proactively tell the primary about their
> slots (like hot_standby_feedback), but I don't think this can be made
> reliable. With cascaded standbys the information has to be propagated
> up through each level, and the propagation lag leaves an unavoidable
> race: by the time the primary learns that a downstream server still
> needs logical WAL, its slots may already be gone, or a new slot could
> be created right after the primary decided to disable.
>

makes sense.

-- 
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/
" Maybe that's what Batman is about. Not winning. But failing, and getting
back up. "

^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-22 13:38  Amit Kapila <amit.kapila16@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 1 reply; 59+ messages in thread

From: Amit Kapila @ 2026-07-22 13:38 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Tue, Jul 14, 2026 at 2:02 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> These races are confined to the narrow window between checking the
> logical decoding status and the new slot becoming visible; once the
> slot is visible, the invalidation performed by the deactivation
> already covers it. So the fix is simple: re-check the logical decoding
> status after the new slot becomes visible.
>

*
- * CheckLogicalDecodingRequirements() must have already errored out if
- * logical decoding is not enabled since we cannot enable the logical
- * decoding status during recovery.
+ * The caller has already checked that logical decoding is enabled via
+ * CheckLogicalDecodingRequirements(), but the status could have been
+ * disabled concurrently before our slot being created: either by
+ * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by
+ * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We
+ * cannot enable logical decoding during recovery, so raise an error.
  */
- Assert(IsLogicalDecodingEnabled());
+ if (!IsLogicalDecodingEnabled())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("logical decoding on standby requires \"effective_wal_level\"
>= \"logical\" on the primary"),
+ errdetail("Logical decoding was concurrently disabled during the
logical replication slot creation.")));

It is not clear after reading the comment above this check what kind
of interlocking would save us from concurrent deactivation by two ways
mentioned by you immediately after this check?

-- 
With Regards,
Amit Kapila.






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-23 11:43  Amit Kapila <amit.kapila16@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 1 reply; 59+ messages in thread

From: Amit Kapila @ 2026-07-23 11:43 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> 0001 is the fix for the originally reported issue, unchanged from the
> previous version.
>

0001 LGTM. This is a separate fix than 0002, so we can proceed with
the commit of this one unless you want to combine the fix for both the
issues and want to make a single commit.

-- 
With Regards,
Amit Kapila.






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-24 07:20  Amit Kapila <amit.kapila16@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Amit Kapila @ 2026-07-24 07:20 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Wed, Jul 22, 2026 at 7:08 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> *
> - * CheckLogicalDecodingRequirements() must have already errored out if
> - * logical decoding is not enabled since we cannot enable the logical
> - * decoding status during recovery.
> + * The caller has already checked that logical decoding is enabled via
> + * CheckLogicalDecodingRequirements(), but the status could have been
> + * disabled concurrently before our slot being created: either by
> + * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by
> + * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We
> + * cannot enable logical decoding during recovery, so raise an error.
>   */
> - Assert(IsLogicalDecodingEnabled());
> + if (!IsLogicalDecodingEnabled())
> + ereport(ERROR,
> + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
> + errmsg("logical decoding on standby requires \"effective_wal_level\"
> >= \"logical\" on the primary"),
> + errdetail("Logical decoding was concurrently disabled during the
> logical replication slot creation.")));
>
> It is not clear after reading the comment above this check what kind
> of interlocking would save us from concurrent deactivation by two ways
> mentioned by you immediately after this check?
>

I checked that before reaching here, we would have marked the slot as
in_use, so the invalidation will invalidate such a slot.

The other observation I had while looking at this patch was: On a
standby, InvalidateObsoleteReplicationSlots() can disable logical
decoding whenever it invalidates the last valid logical slot via
following check:

if (invalidated_logical && !found_valid_logicalslot)
      RequestDisableLogicalDecoding();
RequestDisableLogicalDecoding() isn't guarded against recovery, so a
purely local invalidation (RS_INVAL_HORIZON/WAL_REMOVED/IDLE_TIMEOUT)
makes the standby disable decoding even though the primary still has
it enabled. The standby's status is supposed to follow the primary via
XLOG_LOGICAL_DECODING_STATUS_CHANGE replay, and there's no
self-healing since the primary never sends an "enable". So, won't that
be a problem because after that no new slots will be allowed to be
created on standby and slotsync also won't be able perform sync. Am, I
missing something? If not then probable the above check needs
additional check: "!RecoveryInProgress()".

-- 
With Regards,
Amit Kapila.






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-27 16:05  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-27 16:05 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Fri, Jul 24, 2026 at 12:20 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Wed, Jul 22, 2026 at 7:08 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> > *
> > - * CheckLogicalDecodingRequirements() must have already errored out if
> > - * logical decoding is not enabled since we cannot enable the logical
> > - * decoding status during recovery.
> > + * The caller has already checked that logical decoding is enabled via
> > + * CheckLogicalDecodingRequirements(), but the status could have been
> > + * disabled concurrently before our slot being created: either by
> > + * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by
> > + * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We
> > + * cannot enable logical decoding during recovery, so raise an error.
> >   */
> > - Assert(IsLogicalDecodingEnabled());
> > + if (!IsLogicalDecodingEnabled())
> > + ereport(ERROR,
> > + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
> > + errmsg("logical decoding on standby requires \"effective_wal_level\"
> > >= \"logical\" on the primary"),
> > + errdetail("Logical decoding was concurrently disabled during the
> > logical replication slot creation.")));
> >
> > It is not clear after reading the comment above this check what kind
> > of interlocking would save us from concurrent deactivation by two ways
> > mentioned by you immediately after this check?
> >
>
> I checked that before reaching here, we would have marked the slot as
> in_use, so the invalidation will invalidate such a slot.

Right. Will update the comment to make it clearer.

>
> The other observation I had while looking at this patch was: On a
> standby, InvalidateObsoleteReplicationSlots() can disable logical
> decoding whenever it invalidates the last valid logical slot via
> following check:
>
> if (invalidated_logical && !found_valid_logicalslot)
>       RequestDisableLogicalDecoding();
> RequestDisableLogicalDecoding() isn't guarded against recovery, so a
> purely local invalidation (RS_INVAL_HORIZON/WAL_REMOVED/IDLE_TIMEOUT)
> makes the standby disable decoding even though the primary still has
> it enabled. The standby's status is supposed to follow the primary via
> XLOG_LOGICAL_DECODING_STATUS_CHANGE replay, and there's no
> self-healing since the primary never sends an "enable". So, won't that
> be a problem because after that no new slots will be allowed to be
> created on standby and slotsync also won't be able perform sync. Am, I
> missing something? If not then probable the above check needs
> additional check: "!RecoveryInProgress()".

In this case, the checkpointer will try to disable logical decoding
but does nothing as it's still in recovery. See the
RecoveryInProgress() check in DisableLogicalDecodingIfNecessary().

If we skip calling RequestDisableLogicalDecoding() in this case, we
would end up missing the disable request as it can be interleaved with
the promotion process. Imagine:

1. the startup process begins the promotion, decides the
new_status=true as there is a logical slot (in
UpdateLogicalDecodingStatusEndOfRecovery()).
2. a backend process drops the last logical slot and skips calling
RequestDisableLogicalDecoding() as the recovery status is still
in-progress.
3. the startup completes the
UpdateLogicalDecodingStatusEndOfRecovery(). The logical decoding is
enabled even though there is no logical slot.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-27 16:39  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-27 16:39 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 23, 2026 at 4:43 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > 0001 is the fix for the originally reported issue, unchanged from the
> > previous version.
> >
>
> 0001 LGTM. This is a separate fix than 0002, so we can proceed with
> the commit of this one unless you want to combine the fix for both the
> issues and want to make a single commit.

Agreed and pushed the 0001 patch.

I've updated the comments in the previous-0002 patch, please review it.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments:

v4-0001-Fix-races-between-deactivation-of-logical-decodin.patch (text/x-patch, 17.4K) download From aaa78e32e4f384a3bfc30402a8a6a2850d951e03 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Wed, 15 Jul 2026 11:49:28 -0700 Subject: [PATCH v4] Fix races between deactivation of logical decoding and slot creation. On standbys, logical decoding can be deactivated while a logical slot is being created: either by replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by the end-of-recovery transition upon promotion, which deactivates logical decoding if no valid logical slot exists. Both could interleave with a check of the logical decoding status performed before the new slot becomes visible, because the slot invalidation executed as part of the deactivation cannot find a slot that is not visible yet. For regular slot creation on standbys, EnsureLogicalDecodingEnabled() assumed that logical decoding must still be enabled during recovery since the caller had already checked it, tripping an assertion failure if a concurrent deactivation interleaved. For slot synchronization, the local slot could be created and persisted based on the remote slot information fetched before the deactivation was replayed, leaving a valid slot whose restart_lsn precedes the deactivation. Fix both paths by re-checking the logical decoding status after the new slot becomes visible: regular slot creation raises an error, and slot synchronization skips persisting the slot. If the deactivation happens after the re-check instead, it is guaranteed to invalidate the now-visible slot. Reviewed-by: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Reviewed-by: Amit Kapila <amit.kapila16@gmail.com> Discussion: https://postgr.es/m/CAD21AoDEB99VtNbQdDrNd=1gQupJNGMfW_5kdnxq03Q82EK3ag@mail.gmail.com Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 47 ++++-- src/backend/replication/logical/slotsync.c | 37 ++++ src/backend/replication/slot.c | 2 + src/backend/replication/slotfuncs.c | 13 +- src/backend/replication/walsender.c | 4 +- .../recovery/t/051_effective_wal_level.pl | 158 ++++++++++++++++++ 6 files changed, 246 insertions(+), 15 deletions(-) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 4a690a631da..14cae7f5cd9 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -274,11 +274,10 @@ abort_logical_decoding_activation(int code, Datum arg) /* * Enable logical decoding if disabled. * - * If this function is called during recovery, it simply returns without - * action since the logical decoding status change is not allowed during - * this time. The logical decoding status depends on the status on the primary. - * The caller should use CheckLogicalDecodingRequirements() before calling this - * function to make sure that the logical decoding status can be modified. + * If this function is called during recovery, it just checks that logical + * decoding is still enabled, since the logical decoding status cannot be + * changed during this time. The logical decoding status depends on the + * status on the primary. * * Note that there is no interlock between logical decoding activation * and slot creation. To ensure enabling logical decoding, the caller @@ -298,11 +297,28 @@ EnsureLogicalDecodingEnabled(void) if (RecoveryInProgress()) { /* - * CheckLogicalDecodingRequirements() must have already errored out if - * logical decoding is not enabled since we cannot enable the logical - * decoding status during recovery. + * The caller has already checked that logical decoding is enabled via + * CheckLogicalDecodingRequirements(), but the status could have been + * disabled concurrently before our slot became visible: either by + * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by + * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We + * cannot enable logical decoding during recovery, so raise an error. + * + * Our already-visible slot guarantees that this check doesn't miss a + * concurrent deactivation: UpdateLogicalDecodingStatusEndOfRecovery() + * won't disable logical decoding as it sees our valid slot, and + * replaying a status change record after this check invalidates our + * slot, so this slot creation fails afterwards anyway (by a recovery + * conflict or the requirement re-check in + * CreateInitDecodingContext()). Hence, this check only needs to catch + * deactivations that completed before our slot became visible. */ - Assert(IsLogicalDecodingEnabled()); + if (!IsLogicalDecodingEnabled()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("logical decoding on standby requires \"effective_wal_level\" >= \"logical\" on the primary"), + errdetail("Logical decoding was concurrently disabled during the logical replication slot creation."))); + return; } @@ -602,10 +618,15 @@ UpdateLogicalDecodingStatusEndOfRecovery(void) * already occur due to the checkpointer's asynchronous deactivation * process. * - * For 'disable' case, backend cannot create logical replication slots - * during recovery (see checks in CheckLogicalDecodingRequirements()), - * which prevents a race condition between disabling logical decoding and - * concurrent slot creation. + * For 'disable' case, a backend concurrently creating a logical slot on a + * standby could have passed its CheckLogicalDecodingRequirements() check + * while making its slot visible only after our slot check above. Such a + * backend rechecks the status after creating the slot in + * EnsureLogicalDecodingEnabled() and raises an error if logical decoding + * has been disabled meanwhile, so it cannot end up with a logical slot + * while logical decoding remains disabled. (If recovery has already ended + * by the time of the recheck, the backend instead enables logical + * decoding by itself, which is fine after promotion.) */ if (new_status != LogicalDecodingCtl->logical_decoding_enabled) { diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index d1936823506..e52c22f0c24 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -67,6 +67,7 @@ #include "pgstat.h" #include "postmaster/interrupt.h" #include "replication/logical.h" +#include "replication/logicalctl.h" #include "replication/slotsync.h" #include "replication/snapbuild.h" #include "storage/ipc.h" @@ -717,6 +718,42 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } + /* + * Do not persist the slot if logical decoding got disabled concurrently. + * This can happen if the last logical slot on the primary was dropped + * and the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was + * replayed after we fetched the remote slot information: WAL records + * following the slot's restart_lsn might lack the information required + * by logical decoding, and the slot invalidation performed when + * replaying the record could not find our slot as it was not visible + * yet. + * + * It is important to perform this check after the slot became visible + * and before persisting it. This way, even if the status change record + * is replayed after this check, the replay will invalidate our slot. + * + * If the check fails, we keep the temporary slot and let the caller + * retry; the next cycle fetches the remote slot information again and + * will drop this slot as the remote slot no longer exists. + * + * XXX: this check cannot detect the case where logical decoding is + * already re-enabled by a slot creation on the primary at this point. + * Detecting that would require comparing the slot's restart_lsn with + * the LSN at which logical decoding was last enabled. + */ + if (!IsLogicalDecodingEnabled()) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding was concurrently disabled.")); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + ReplicationSlotPersist(); ereport(LOG, diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c index c7ab82a28e1..1a0ff682068 100644 --- a/src/backend/replication/slot.c +++ b/src/backend/replication/slot.c @@ -420,6 +420,8 @@ ReplicationSlotCreate(const char *name, bool db_specific, errmsg("cannot enable failover for a temporary replication slot")); } + INJECTION_POINT("replication-slot-create-begin", NULL); + /* * If some other backend ran this code concurrently with us, we'd likely * both allocate the same slot, and that would be bad. We'd also be at diff --git a/src/backend/replication/slotfuncs.c b/src/backend/replication/slotfuncs.c index 16fbd383735..813180fece7 100644 --- a/src/backend/replication/slotfuncs.c +++ b/src/backend/replication/slotfuncs.c @@ -153,7 +153,18 @@ create_logical_replication_slot(char *name, char *plugin, * decoding context. */ EnsureLogicalDecodingEnabled(); - Assert(IsLogicalDecodingEnabled()); + + /* + * Outside of recovery, holding a valid logical slot prevents logical + * decoding from being disabled. During recovery, however, replaying a + * status change record can disable it at any time regardless of slot + * existence, so we cannot assert that it is still enabled here. That is + * harmless: such a replay invalidates our already-visible slot, so this + * slot creation fails afterwards (by a recovery conflict or the + * requirement re-check in CreateInitDecodingContext()) instead of leaving + * a usable slot behind. + */ + Assert(RecoveryInProgress() || IsLogicalDecodingEnabled()); /* * Create logical decoding context to find start point or, if we don't diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c index 35ebc7e61c8..c65dd324325 100644 --- a/src/backend/replication/walsender.c +++ b/src/backend/replication/walsender.c @@ -1372,7 +1372,9 @@ CreateReplicationSlot(CreateReplicationSlotCmd *cmd) * logical decoding context. */ EnsureLogicalDecodingEnabled(); - Assert(IsLogicalDecodingEnabled()); + + /* See the comment in create_logical_replication_slot() */ + Assert(RecoveryInProgress() || IsLogicalDecodingEnabled()); ctx = CreateInitDecodingContext(cmd->plugin, NIL, need_full_snapshot, false, diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 2cf2ea6546d..a685c2cdcd9 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -507,6 +507,164 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled test_wal_level($primary, "replica|logical", "effective_wal_level remains 'logical' even after the concurrent activation is interrupted" ); + + # 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 their slot becomes visible 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. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot2')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql( + 'postgres', qq[ +alter system set autovacuum = off; +select pg_reload_conf(); +]); + + # Initialize standby5 node, setting up the requirements for slot + # synchronization. + $primary->safe_psql('postgres', + qq[select pg_create_physical_replication_slot('phys_slot')]); + my $standby5 = PostgreSQL::Test::Cluster->new('standby5'); + $standby5->init_from_backup($primary, 'my_backup', has_streaming => 1); + my $connstr = $primary->connstr; + $standby5->append_conf( + 'postgresql.conf', qq[ +primary_slot_name = 'phys_slot' +primary_conninfo = '$connstr dbname=postgres' +hot_standby_feedback = on +]); + $standby5->start; + + # Test that slot synchronization doesn't persist a slot whose remote + # slot information was fetched before a deactivation was replayed. + # Otherwise, the slot would survive with a restart_lsn preceding the + # deactivation, as the slot invalidation performed by the replay cannot + # find the slot that is not visible yet. + + # Enable logical decoding by creating a failover-enabled slot, and wait + # for the standby to replay the activation. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5"); + + # Start slot synchronization, stopping it after fetching the remote slot + # information but before creating the local slot. + my $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); + + # Drop the last logical slot on the primary and wait for the standby to + # replay the deactivation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|replica", + "logical decoding got deactivated on standby5"); + + # Resume the slot synchronization; it must skip persisting the slot. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('replication-slot-create-begin')]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot"/, $log_offset); + $psql_sync_slot->quit; + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5"); + + # Test that logical slot creation on a standby fails cleanly if logical + # decoding is concurrently deactivated by the end-of-recovery transition + # upon promotion, which cannot find the slot that is not visible yet. + + # Enable logical decoding again. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('test_slot3', 'test_decoding')] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated again on standby5"); + + # Hold the startup process right after the end-of-recovery status + # change, before recovery actually ends. + $standby5->safe_psql('postgres', + qq[select injection_points_attach('startup-logical-decoding-status-change-end-of-recovery', 'wait')] + ); + + # Start creating a logical slot, stopping it before the slot becomes + # visible. + $psql_create_slot = + $standby5->background_psql('postgres', on_error_stop => 0); + $psql_create_slot->query_until( + qr/create_standby5_slot/, + q(\echo create_standby5_slot +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_create_logical_replication_slot('standby5_slot', 'test_decoding'); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); + + # Promote the standby without waiting; the startup process deactivates + # logical decoding as no logical slot is visible, and stops at the + # injection point, still in recovery. + $standby5->safe_psql('postgres', qq[select pg_promote(false)]); + $standby5->wait_for_event('startup', + 'startup-logical-decoding-status-change-end-of-recovery'); + + # Resume the slot creation; it must fail cleanly. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('replication-slot-create-begin')]); + $standby5->wait_for_log( + qr/ERROR: .* logical decoding on standby requires "effective_wal_level" >= "logical" on the primary/, + $log_offset); + $psql_create_slot->quit; + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no slot is left behind on standby5"); + + # Let the promotion complete. + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('startup-logical-decoding-status-change-end-of-recovery')] + ); + $standby5->safe_psql('postgres', + qq[select injection_points_detach('startup-logical-decoding-status-change-end-of-recovery')] + ); + $standby5->poll_query_until('postgres', + qq[select not pg_is_in_recovery()]) + or die "timed out waiting for promotion"; + + # Retrying the slot creation on the promoted standby5 must succeed and + # activate logical decoding. + $standby5->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('standby5_slot', 'test_decoding')] + ); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on the promoted standby5 after retry" + ); } $primary->stop; -- 2.54.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-29 05:28  Amit Kapila <amit.kapila16@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 0 replies; 59+ messages in thread

From: Amit Kapila @ 2026-07-29 05:28 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Mon, Jul 27, 2026 at 9:36 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Fri, Jul 24, 2026 at 12:20 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> > The other observation I had while looking at this patch was: On a
> > standby, InvalidateObsoleteReplicationSlots() can disable logical
> > decoding whenever it invalidates the last valid logical slot via
> > following check:
> >
> > if (invalidated_logical && !found_valid_logicalslot)
> >       RequestDisableLogicalDecoding();
> > RequestDisableLogicalDecoding() isn't guarded against recovery, so a
> > purely local invalidation (RS_INVAL_HORIZON/WAL_REMOVED/IDLE_TIMEOUT)
> > makes the standby disable decoding even though the primary still has
> > it enabled. The standby's status is supposed to follow the primary via
> > XLOG_LOGICAL_DECODING_STATUS_CHANGE replay, and there's no
> > self-healing since the primary never sends an "enable". So, won't that
> > be a problem because after that no new slots will be allowed to be
> > created on standby and slotsync also won't be able perform sync. Am, I
> > missing something? If not then probable the above check needs
> > additional check: "!RecoveryInProgress()".
>
> In this case, the checkpointer will try to disable logical decoding
> but does nothing as it's still in recovery. See the
> RecoveryInProgress() check in DisableLogicalDecodingIfNecessary().
>
> If we skip calling RequestDisableLogicalDecoding() in this case, we
> would end up missing the disable request as it can be interleaved with
> the promotion process. Imagine:
>
> 1. the startup process begins the promotion, decides the
> new_status=true as there is a logical slot (in
> UpdateLogicalDecodingStatusEndOfRecovery()).
> 2. a backend process drops the last logical slot and skips calling
> RequestDisableLogicalDecoding() as the recovery status is still
> in-progress.
> 3. the startup completes the
> UpdateLogicalDecodingStatusEndOfRecovery(). The logical decoding is
> enabled even though there is no logical slot.
>

Thanks, I missed the check in DisableLogicalDecodingIfNecessary(). But
will it be better to add a comment atop that check and also atop
RequestDisableLogicalDecoding()? If so, how about something like
attached?

-- 
With Regards,
Amit Kapila.

Attachments:

v1_fix_comments_1.patch (application/octet-stream, 1.3K) download diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 4a690a631da..e647cd74c27 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -429,6 +429,11 @@ EnableLogicalDecoding(void) * * Note that this function does not verify whether logical slots exist. The * checkpointer will verify if logical decoding should actually be disabled. + * + * This may be called during recovery, for example when a standby invalidates + * its last valid logical slot. That is safe because the queued request is only + * acted upon outside recovery. See the RecoveryInProgress() check in + * DisableLogicalDecodingIfNecessary(). */ void RequestDisableLogicalDecoding(void) @@ -471,6 +476,14 @@ DisableLogicalDecodingIfNecessary(void) */ Assert(!MyReplicationSlot); + /* + * During recovery the logical decoding status follows the primary via WAL + * replay, so we must not disable it here. A pending_disable request queued + * during recovery, for example by a local slot invalidation, is + * intentionally left for the end-of-recovery transition or the + * post-promotion checkpointer to act on. See + * UpdateLogicalDecodingStatusEndOfRecovery(). + */ if (RecoveryInProgress()) return;
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-29 10:21  Amit Kapila <amit.kapila16@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Amit Kapila @ 2026-07-29 10:21 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Mon, Jul 27, 2026 at 10:10 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> Agreed and pushed the 0001 patch.
>
> I've updated the comments in the previous-0002 patch, please review it.
>

In the comments you mentioned 'already-visible slot' as follows: "Our
already-visible slot guarantees that this check doesn't miss ..." but
we normally don't use visibility term for slots (it is used primarily
for tuples). I think you mean to say that its in_use flag is set, I
tried to slightly modify that part of the comment in the attached.
See, if that looks okay to you.

Apart from that, I ran the added test on my Windows machine and it
failed, attached find the required log.

-- 
With Regards,
Amit Kapila.

Attachments:

v4_topup_comment-fixup.patch (application/octet-stream, 1.1K) download diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 14cae7f5cd9..8bdb718812f 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -304,8 +304,10 @@ EnsureLogicalDecodingEnabled(void) * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We * cannot enable logical decoding during recovery, so raise an error. * - * Our already-visible slot guarantees that this check doesn't miss a - * concurrent deactivation: UpdateLogicalDecodingStatusEndOfRecovery() + * Our slot is already visible in shared memory (its in_use flag is + * set, so a concurrent deactivation's slot invalidation can find it), + * which guarantees that this check doesn't miss a concurrent + * deactivation: UpdateLogicalDecodingStatusEndOfRecovery() * won't disable logical decoding as it sees our valid slot, and * replaying a status change record after this check invalidates our * slot, so this slot creation fails afterwards anyway (by a recovery
051_effective_wal_level_standby5.log (application/octet-stream, 3.3K) download regress_log_051_effective_wal_level (application/octet-stream, 21.6K) download ^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-30 07:06  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-30 07:06 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Wed, Jul 29, 2026 at 3:21 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Mon, Jul 27, 2026 at 10:10 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > Agreed and pushed the 0001 patch.
> >
> > I've updated the comments in the previous-0002 patch, please review it.
> >
>
> In the comments you mentioned 'already-visible slot' as follows: "Our
> already-visible slot guarantees that this check doesn't miss ..." but
> we normally don't use visibility term for slots (it is used primarily
> for tuples). I think you mean to say that its in_use flag is set, I
> tried to slightly modify that part of the comment in the attached.
> See, if that looks okay to you.

Fair point. I've updated the comments and commit message not to use
the visibility term.

> Apart from that, I ran the added test on my Windows machine and it
> failed, attached find the required log.

Thank you for testing it. It seems to be reproducible also on CI, and
I believe I've fixed the issue.

I've attached the patch. Please review it.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments:

v5-0001-Fix-races-between-deactivation-of-logical-decodin.patch (text/x-patch, 18.7K) download From a10060946c7b604eb232f09183f79646bde1ba1b Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Wed, 15 Jul 2026 11:49:28 -0700 Subject: [PATCH v5] Fix races between deactivation of logical decoding and slot creation. On standbys, logical decoding can be deactivated while a logical slot is being created: either by replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by the end-of-recovery transition upon promotion, which deactivates logical decoding if no valid logical slot exists. Both could interleave with a check of the logical decoding status performed before creating a new slot because the slot invalidation executed as part of the deactivation cannot find a slot being created. For regular slot creation on standbys, EnsureLogicalDecodingEnabled() assumed that logical decoding must still be enabled during recovery since the caller had already checked it, tripping an assertion failure if a concurrent deactivation interleaved. For slot synchronization, the local slot could be created and persisted based on the remote slot information fetched before the deactivation was replayed, leaving a valid slot whose restart_lsn precedes the deactivation. Fix both paths by re-checking the logical decoding status after the new slot has been created: regular slot creation raises an error, and slot synchronization skips persisting the slot. If the deactivation happens after the re-check instead, it is guaranteed to invalidate the newly created slot. Reviewed-by: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Reviewed-by: Amit Kapila <amit.kapila16@gmail.com> Discussion: https://postgr.es/m/CAD21AoDEB99VtNbQdDrNd=1gQupJNGMfW_5kdnxq03Q82EK3ag@mail.gmail.com Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 62 +++++-- src/backend/replication/logical/slotsync.c | 36 ++++ src/backend/replication/slot.c | 2 + src/backend/replication/slotfuncs.c | 11 +- src/backend/replication/walsender.c | 4 +- .../recovery/t/051_effective_wal_level.pl | 161 ++++++++++++++++++ 6 files changed, 261 insertions(+), 15 deletions(-) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 4a690a631da..e5340880fa7 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -274,11 +274,10 @@ abort_logical_decoding_activation(int code, Datum arg) /* * Enable logical decoding if disabled. * - * If this function is called during recovery, it simply returns without - * action since the logical decoding status change is not allowed during - * this time. The logical decoding status depends on the status on the primary. - * The caller should use CheckLogicalDecodingRequirements() before calling this - * function to make sure that the logical decoding status can be modified. + * If this function is called during recovery, it just checks that logical + * decoding is still enabled, since the logical decoding status cannot be + * changed during this time. The logical decoding status depends on the + * status on the primary. * * Note that there is no interlock between logical decoding activation * and slot creation. To ensure enabling logical decoding, the caller @@ -298,11 +297,30 @@ EnsureLogicalDecodingEnabled(void) if (RecoveryInProgress()) { /* - * CheckLogicalDecodingRequirements() must have already errored out if - * logical decoding is not enabled since we cannot enable the logical - * decoding status during recovery. + * The caller has already checked that logical decoding is enabled via + * CheckLogicalDecodingRequirements(), but the status could have been + * disabled concurrently before we created our slot: either by + * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by + * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We + * cannot enable logical decoding during recovery, so raise an error. + * + * Our slot has already been created, so its in_use flag is set and + * the slot scans performed by a deactivation can see it. It + * guarantees that this check doesn't miss a concurrent deactivation: + * UpdateLogicalDecodingStatusEndOfRecovery() won't disable logical + * decoding since CheckLogicalSlotExists() finds our valid slot, and + * replaying a status change record after this check invalidates our + * slot, so this slot creation fails afterwards anyway (by a recovery + * conflict or the requirement re-check in + * CreateInitDecodingContext()). Hence, this check only needs to catch + * deactivations that completed before our slot's in_use flag was set. */ - Assert(IsLogicalDecodingEnabled()); + if (!IsLogicalDecodingEnabled()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("logical decoding on standby requires \"effective_wal_level\" >= \"logical\" on the primary"), + errdetail("Logical decoding was concurrently disabled during the logical replication slot creation."))); + return; } @@ -429,6 +447,11 @@ EnableLogicalDecoding(void) * * Note that this function does not verify whether logical slots exist. The * checkpointer will verify if logical decoding should actually be disabled. + * + * This may be called during recovery, for example when a standby invalidates + * its last valid logical slot. That is safe because the queued request is only + * acted upon outside recovery. See the RecoveryInProgress() check in + * DisableLogicalDecodingIfNecessary(). */ void RequestDisableLogicalDecoding(void) @@ -471,6 +494,14 @@ DisableLogicalDecodingIfNecessary(void) */ Assert(!MyReplicationSlot); + /* + * During recovery the logical decoding status follows the primary via WAL + * replay, so we must not disable it here. A pending_disable request + * queued during recovery, for example by a local slot invalidation, is + * intentionally left for the end-of-recovery transition or the + * post-promotion checkpointer to act on. See + * UpdateLogicalDecodingStatusEndOfRecovery(). + */ if (RecoveryInProgress()) return; @@ -602,10 +633,15 @@ UpdateLogicalDecodingStatusEndOfRecovery(void) * already occur due to the checkpointer's asynchronous deactivation * process. * - * For 'disable' case, backend cannot create logical replication slots - * during recovery (see checks in CheckLogicalDecodingRequirements()), - * which prevents a race condition between disabling logical decoding and - * concurrent slot creation. + * For 'disable' case, a backend concurrently creating a logical slot on a + * standby could have passed its CheckLogicalDecodingRequirements() check + * when creating its slot only after our slot check above. Such a backend + * rechecks the status after creating the slot in + * EnsureLogicalDecodingEnabled() and raises an error if logical decoding + * has been disabled meanwhile, so it cannot end up with a logical slot + * while logical decoding remains disabled. (If recovery has already ended + * by the time of the recheck, the backend instead enables logical + * decoding by itself, which is fine after promotion.) */ if (new_status != LogicalDecodingCtl->logical_decoding_enabled) { diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index d1936823506..c0403893e23 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -67,6 +67,7 @@ #include "pgstat.h" #include "postmaster/interrupt.h" #include "replication/logical.h" +#include "replication/logicalctl.h" #include "replication/slotsync.h" #include "replication/snapbuild.h" #include "storage/ipc.h" @@ -717,6 +718,41 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } + /* + * Do not persist the slot if logical decoding got disabled concurrently. + * This can happen if the last logical slot on the primary was dropped and + * the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was + * replayed after we fetched the remote slot information: WAL records + * following the slot's restart_lsn might lack the information required by + * logical decoding, and the slot invalidation performed when replaying + * the record could not find our slot as it was not created yet. + * + * It is important to perform this check after creating the slot and + * before persisting it. This way, even if the status change record is + * replayed after this check, the replay will invalidate our slot. + * + * If the check fails, we keep the temporary slot and let the caller + * retry; the next cycle fetches the remote slot information again and + * will drop this slot as the remote slot no longer exists. + * + * XXX: this check cannot detect the case where logical decoding is + * already re-enabled by a slot creation on the primary at this point. + * Detecting that would require comparing the slot's restart_lsn with the + * LSN at which logical decoding was last enabled. + */ + if (!IsLogicalDecodingEnabled()) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding was concurrently disabled.")); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + ReplicationSlotPersist(); ereport(LOG, diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c index c7ab82a28e1..1a0ff682068 100644 --- a/src/backend/replication/slot.c +++ b/src/backend/replication/slot.c @@ -420,6 +420,8 @@ ReplicationSlotCreate(const char *name, bool db_specific, errmsg("cannot enable failover for a temporary replication slot")); } + INJECTION_POINT("replication-slot-create-begin", NULL); + /* * If some other backend ran this code concurrently with us, we'd likely * both allocate the same slot, and that would be bad. We'd also be at diff --git a/src/backend/replication/slotfuncs.c b/src/backend/replication/slotfuncs.c index 16fbd383735..fdeb6a23d7b 100644 --- a/src/backend/replication/slotfuncs.c +++ b/src/backend/replication/slotfuncs.c @@ -153,7 +153,16 @@ create_logical_replication_slot(char *name, char *plugin, * decoding context. */ EnsureLogicalDecodingEnabled(); - Assert(IsLogicalDecodingEnabled()); + + /* + * Outside of recovery, holding a valid logical slot prevents logical + * decoding from being disabled. During recovery, however, replaying a + * status change record can disable it at any time regardless of slot + * existence, so we cannot assert that it is still enabled here. That is + * harmless: such a replay invalidates slots, so this slot creation fails + * afterwards. + */ + Assert(RecoveryInProgress() || IsLogicalDecodingEnabled()); /* * Create logical decoding context to find start point or, if we don't diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c index 35ebc7e61c8..c65dd324325 100644 --- a/src/backend/replication/walsender.c +++ b/src/backend/replication/walsender.c @@ -1372,7 +1372,9 @@ CreateReplicationSlot(CreateReplicationSlotCmd *cmd) * logical decoding context. */ EnsureLogicalDecodingEnabled(); - Assert(IsLogicalDecodingEnabled()); + + /* See the comment in create_logical_replication_slot() */ + Assert(RecoveryInProgress() || IsLogicalDecodingEnabled()); ctx = CreateInitDecodingContext(cmd->plugin, NIL, need_full_snapshot, false, diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 2cf2ea6546d..5990d76888d 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -467,6 +467,8 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled wait_for_logical_decoding_disabled($primary); pass("the activation process aborted"); + $psql_create_slot->quit; + # Test concurrent activation processes run and one is interrupted. $psql_create_slot = $primary->background_psql('postgres'); @@ -507,6 +509,165 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled test_wal_level($primary, "replica|logical", "effective_wal_level remains 'logical' even after the concurrent activation is interrupted" ); + + $psql_create_slot->quit; + + # 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. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot2')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql( + 'postgres', qq[ +alter system set autovacuum = off; +select pg_reload_conf(); +]); + + # Initialize standby5 node, setting up the requirements for slot + # synchronization. + $primary->safe_psql('postgres', + qq[select pg_create_physical_replication_slot('phys_slot')]); + my $standby5 = PostgreSQL::Test::Cluster->new('standby5'); + $standby5->init_from_backup($primary, 'my_backup', has_streaming => 1); + my $connstr = $primary->connstr; + $standby5->append_conf( + 'postgresql.conf', qq[ +primary_slot_name = 'phys_slot' +primary_conninfo = '$connstr dbname=postgres' +hot_standby_feedback = on +]); + $standby5->start; + + # Test that slot synchronization doesn't persist a slot whose remote + # slot information was fetched before a deactivation was replayed. + # Otherwise, the slot would survive with a restart_lsn preceding the + # deactivation, as the slot invalidation performed by the replay cannot + # find the slot that is not created yet. + + # Enable logical decoding by creating a failover-enabled slot, and wait + # for the standby to replay the activation. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5"); + + # Start slot synchronization, stopping it after fetching the remote slot + # information but before creating the local slot. + my $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); + + # Drop the last logical slot on the primary and wait for the standby to + # replay the deactivation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|replica", + "logical decoding got deactivated on standby5"); + + # Resume the slot synchronization; it must skip persisting the slot. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('replication-slot-create-begin')]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot"/, $log_offset); + $psql_sync_slot->quit; + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5"); + + # Test that logical slot creation on a standby fails cleanly if logical + # decoding is concurrently deactivated by the end-of-recovery transition + # upon promotion, which cannot find the slot that is not created yet. + + # Enable logical decoding again. + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('test_slot3', 'test_decoding')] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated again on standby5"); + + # Hold the startup process right after the end-of-recovery status + # change, before recovery actually ends. + $standby5->safe_psql('postgres', + qq[select injection_points_attach('startup-logical-decoding-status-change-end-of-recovery', 'wait')] + ); + + # Start creating a logical slot, stopping it before creating the slot. + $psql_create_slot = + $standby5->background_psql('postgres', on_error_stop => 0); + $psql_create_slot->query_until( + qr/create_standby5_slot/, + q(\echo create_standby5_slot +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_create_logical_replication_slot('standby5_slot', 'test_decoding'); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); + + # Promote the standby without waiting; the startup process deactivates + # logical decoding as no logical slot, and stops at the injection point, + # still in recovery. + $standby5->safe_psql('postgres', qq[select pg_promote(false)]); + $standby5->wait_for_event('startup', + 'startup-logical-decoding-status-change-end-of-recovery'); + + # Resume the slot creation; it must fail cleanly. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('replication-slot-create-begin')]); + $standby5->wait_for_log( + qr/ERROR: .* logical decoding on standby requires "effective_wal_level" >= "logical" on the primary/, + $log_offset); + $psql_create_slot->quit; + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no slot is left behind on standby5"); + + # Let the promotion complete. + $standby5->safe_psql('postgres', + qq[select injection_points_wakeup('startup-logical-decoding-status-change-end-of-recovery')] + ); + $standby5->safe_psql('postgres', + qq[select injection_points_detach('startup-logical-decoding-status-change-end-of-recovery')] + ); + $standby5->poll_query_until('postgres', + qq[select not pg_is_in_recovery()]) + or die "timed out waiting for promotion"; + + # Retrying the slot creation on the promoted standby5 must succeed and + # activate logical decoding. + $standby5->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('standby5_slot', 'test_decoding')] + ); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on the promoted standby5 after retry" + ); } $primary->stop; -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-30 09:00  Amit Kapila <amit.kapila16@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Amit Kapila @ 2026-07-30 09:00 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 30, 2026 at 12:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> Thank you for testing it. It seems to be reproducible also on CI, and
> I believe I've fixed the issue.
>
> I've attached the patch. Please review it.
>

LGTM.

-- 
With Regards,
Amit Kapila.





^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-30 20:58  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-30 20:58 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 30, 2026 at 2:00 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Thu, Jul 30, 2026 at 12:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > Thank you for testing it. It seems to be reproducible also on CI, and
> > I believe I've fixed the issue.
> >
> > I've attached the patch. Please review it.
> >
>
> LGTM.

Thank you for reviewing the patch. Pushed.

... but some buildfarm members are unhappy. I'm working on it.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-30 21:48  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-30 21:48 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 30, 2026 at 1:58 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Thu, Jul 30, 2026 at 2:00 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> > On Thu, Jul 30, 2026 at 12:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > >
> > > Thank you for testing it. It seems to be reproducible also on CI, and
> > > I believe I've fixed the issue.
> > >
> > > I've attached the patch. Please review it.
> > >
> >
> > LGTM.
>
> Thank you for reviewing the patch. Pushed.
>
> ... but some buildfarm members are unhappy. I'm working on it.
>

I've reproduced the issue on local and confirmed the root cause; two
background psql sessions in the TAP test run with ON_ERROR_STOP=1 and
got canceled by pg_cancel_backend(), so psql exited as soon as the
cancelation error arrived. I've attached the patch that fixes the
problem. I'm waiting for CI to check if the tests still pass on other
environments.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments:

0001-Fix-background-psql-session-cleanup-in-051_effective.patch (text/x-patch, 2.8K) download From 13524f3c11621442fbe9e5bb7e3105ccc2afd8ff Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Thu, 30 Jul 2026 14:32:15 -0700 Subject: [PATCH] Fix background psql session cleanup in 051_effective_wal_level.pl. Two background psql sessions in this test have their slot creation canceled by pg_cancel_backend(). Both ran with the default ON_ERROR_STOP=1 and ended their script with \q, so psql exited as soon as the cancellation error arrived. BackgroundPsql::quit() then appends another \q to the session, which fails against the already-closed pipe. Run both sessions with on_error_stop => 0 and drop the trailing \q, so that psql stays at the prompt after reporting the error and quit(). Reviewed-by: Discussion: https://postgr.es/m/CAD21AoCZY1fKYgfkvHGWGiXpatUKd23FSLnDCL4m9bWFjdXNZw@mail.gmail.com Backpatch-through: 19 --- src/test/recovery/t/051_effective_wal_level.pl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 02f750097bd..11bf4cb6134 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -438,7 +438,8 @@ select pg_drop_replication_slot('slot_2'); # Start a psql session to test the case where the activation process is # interrupted. - $psql_create_slot = $primary->background_psql('postgres'); + $psql_create_slot = + $primary->background_psql('postgres', on_error_stop => 0); # Start the logical decoding activation process upon creating the logical # slot, but it will wait due to the injection point. @@ -448,7 +449,6 @@ select pg_drop_replication_slot('slot_2'); select injection_points_set_local(); select injection_points_attach('logical-decoding-activation', 'wait'); select pg_create_logical_replication_slot('slot_canceled', 'pgoutput'); -\q )); $primary->wait_for_event('client backend', 'logical-decoding-activation'); @@ -470,7 +470,8 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled $psql_create_slot->quit; # Test concurrent activation processes run and one is interrupted. - $psql_create_slot = $primary->background_psql('postgres'); + $psql_create_slot = + $primary->background_psql('postgres', on_error_stop => 0); # Start a psql session and stops in the middle of the activation # process. @@ -480,7 +481,6 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled select injection_points_set_local(); select injection_points_attach('logical-decoding-activation', 'wait'); select pg_create_logical_replication_slot('slot_canceled2', 'pgoutput'); -\q )); $primary->wait_for_event('client backend', 'logical-decoding-activation'); note("injection_point 'logical-decoding-activation' is reached"); -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-31 00:52  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Tom Lane @ 2026-07-31 00:52 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Masahiko Sawada <sawada.mshk@gmail.com> writes:
> I've reproduced the issue on local and confirmed the root cause; two
> background psql sessions in the TAP test run with ON_ERROR_STOP=1 and
> got canceled by pg_cancel_backend(), so psql exited as soon as the
> cancelation error arrived. I've attached the patch that fixes the
> problem. I'm waiting for CI to check if the tests still pass on other
> environments.

The buildfarm looks like this has made 051_effective_wal_level.pl
less stable, not more so.  The failures all look like

[18:37:44.952](0.014s) # injection_point 'logical-decoding-activation' is reached
[18:37:44.982](0.030s) ok 35 - the activation process aborted
[18:37:44.982](0.001s) # die: ack Broken pipe: write( 13, '\\q
# ' ) at /usr/share/perl5/vendor_perl/IPC/Run/IO.pm line 550.
[18:37:44.982](0.000s) 1..35
ack Broken pipe: write( 13, '\\q
' ) at /usr/share/perl5/vendor_perl/IPC/Run/IO.pm line 550.
# Postmaster PID for node "primary" is 81208
### Stopping node "primary" using mode immediate

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-31 03:49  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-07-31 03:49 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 30, 2026 at 5:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Masahiko Sawada <sawada.mshk@gmail.com> writes:
> > I've reproduced the issue on local and confirmed the root cause; two
> > background psql sessions in the TAP test run with ON_ERROR_STOP=1 and
> > got canceled by pg_cancel_backend(), so psql exited as soon as the
> > cancelation error arrived. I've attached the patch that fixes the
> > problem. I'm waiting for CI to check if the tests still pass on other
> > environments.
>
> The buildfarm looks like this has made 051_effective_wal_level.pl
> less stable, not more so.  The failures all look like
>
> [18:37:44.952](0.014s) # injection_point 'logical-decoding-activation' is reached
> [18:37:44.982](0.030s) ok 35 - the activation process aborted
> [18:37:44.982](0.001s) # die: ack Broken pipe: write( 13, '\\q
> # ' ) at /usr/share/perl5/vendor_perl/IPC/Run/IO.pm line 550.
> [18:37:44.982](0.000s) 1..35
> ack Broken pipe: write( 13, '\\q
> ' ) at /usr/share/perl5/vendor_perl/IPC/Run/IO.pm line 550.
> # Postmaster PID for node "primary" is 81208
> ### Stopping node "primary" using mode immediate

What does the buildfarm member produce the above logs? Many buildfarm
members failed with that error due to commit 6a80179f6b0, but I've not
seen further failures since pushing commit 18f9785e0b3.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-07-31 04:00  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 1 reply; 59+ messages in thread

From: Tom Lane @ 2026-07-31 04:00 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Masahiko Sawada <sawada.mshk@gmail.com> writes:
> On Thu, Jul 30, 2026 at 5:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> The buildfarm looks like this has made 051_effective_wal_level.pl
>> less stable, not more so.  The failures all look like

> What does the buildfarm member produce the above logs? Many buildfarm
> members failed with that error due to commit 6a80179f6b0, but I've not
> seen further failures since pushing commit 18f9785e0b3.

Ah, you are right, there are no failures later than 6aba42c.  I was
misled by the fact that several of the complaining animals are still
red because they've not run since then.  Sorry for the noise.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-08-01 05:42  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 0 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-08-01 05:42 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 30, 2026 at 9:01 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Masahiko Sawada <sawada.mshk@gmail.com> writes:
> > On Thu, Jul 30, 2026 at 5:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> >> The buildfarm looks like this has made 051_effective_wal_level.pl
> >> less stable, not more so.  The failures all look like
>
> > What does the buildfarm member produce the above logs? Many buildfarm
> > members failed with that error due to commit 6a80179f6b0, but I've not
> > seen further failures since pushing commit 18f9785e0b3.
>
> Ah, you are right, there are no failures later than 6aba42c.  I was
> misled by the fact that several of the complaining animals are still
> red because they've not run since then.  Sorry for the noise.

No problem, thank you for the confirmation.

I've confirmed that the fix made the buildfarm green again, so I've
marked this open item as resolved.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-22 06:32  Nikolay Samokhvalov <nik@postgres.ai>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 1 reply; 59+ messages in thread

From: Nikolay Samokhvalov @ 2026-09-22 06:32 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
<sawada.mshk@gmail.com> wrote:
> For slot synchronization, the local slot could be created and
> persisted based on the remote slot information fetched before the
> deactivation was replayed, leaving a valid slot whose restart_lsn
> precedes the deactivation. Decoding such a slot after a failover fails
> with:
>
> ERROR: unexpected logical decoding status change 0
>
> These races are confined to the narrow window between checking the
> logical decoding status and the new slot becoming visible; once the
> slot is visible, the invalidation performed by the deactivation
> already covers it. So the fix is simple: re-check the logical decoding
> status after the new slot becomes visible. Regular slot creation
> raises an error and slot synchronization skips persisting the slot. If
> the deactivation happens after the recheck instead, it is guaranteed
> to invalidate the now-visible slot as usual. The attached 0002
> implements this.

The disable/re-enable case described in the comment above the final
IsLogicalDecodingEnabled() check in update_and_persist_local_synced_slot() is
reachable.

On b73d13c3, the reproducer uses this sequence:

1. Slot sync fetches failover slot S and pauses at
replication-slot-create-begin, before creating the local slot.
2. The primary drops S. The standby replays the logical-decoding
deactivation while no local S exists to invalidate.
3. The primary recreates S. The standby replays the reactivation.
4. The old slot sync resumes with the first incarnation's restart_lsn.

The final IsLogicalDecodingEnabled() check now returns true, so the old slot
information is persisted. After promoting the standby, decoding that slot
fails with:

ERROR: unexpected logical decoding status change 0

The attached patch adds a logical-decoding status generation. Slot sync
records it before fetching remote slot information and refuses to persist a
new slot if the generation changed in the meantime. It drops the temporary
slot so that the next attempt fetches the current incarnation.

The new injection-point test fails without the fix because the stale slot is
persisted. With the fix, it verifies that the replacement slot is fetched
and that decoding succeeds after promotion. The existing
051_effective_wal_level test and the core regression tests also pass.

This work was done by our new AI harness for Postgres testing.

Nik

Attachments:

v1-0001-fix-slotsync-logical-decoding-status-aba.patch (application/x-patch, 11.5K) download From 952bd42f9ed3ab2e392e2760b6148d16a2c721b6 Mon Sep 17 00:00:00 2001 From: Nik Samokhvalov <nik@postgres.ai> Date: Mon, 21 Sep 2026 22:14:53 -0700 Subject: [PATCH v1] Fix slot sync across logical decoding disable/re-enable Slot synchronization checks whether logical decoding is enabled before persisting a newly created slot. That misses a disable/re-enable cycle: the old synchronization can persist slot information fetched before the cycle, leaving a slot whose restart LSN precedes the deactivation record. Decoding from that slot after promotion then fails with an unexpected logical decoding status change. Track a generation for logical decoding status changes. Record it before fetching remote slots and require both an unchanged generation and enabled status before persistence. If the check fails, drop the temporary slot so the next attempt refetches the current incarnation. Add an injection-point test for the disable/re-enable race. --- src/backend/replication/logical/logicalctl.c | 39 ++++++++ src/backend/replication/logical/slotsync.c | 31 +++--- src/include/replication/logicalctl.h | 2 + src/test/recovery/meson.build | 1 + src/test/recovery/t/057_slotsync_wal_level.pl | 98 +++++++++++++++++++ 5 files changed, 160 insertions(+), 11 deletions(-) create mode 100644 src/test/recovery/t/057_slotsync_wal_level.pl diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index e5340880fa..27bc092d6b 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -95,6 +95,9 @@ typedef struct LogicalDecodingCtlData /* True if logical decoding might need to be disabled */ bool pending_disable; + + /* Incremented whenever logical_decoding_enabled changes */ + uint64 status_generation; } LogicalDecodingCtlData; static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; @@ -210,6 +213,38 @@ IsLogicalDecodingEnabled(void) return enabled; } +/* + * Return the generation of the current logical decoding status. + */ +uint64 +GetLogicalDecodingStatusGeneration(void) +{ + uint64 generation; + + LWLockAcquire(LogicalDecodingControlLock, LW_SHARED); + generation = LogicalDecodingCtl->status_generation; + LWLockRelease(LogicalDecodingControlLock); + + return generation; +} + +/* + * Return true if logical decoding is enabled and its status has not changed + * since the given generation was read. + */ +bool +LogicalDecodingStatusMatches(uint64 generation) +{ + bool matches; + + LWLockAcquire(LogicalDecodingControlLock, LW_SHARED); + matches = LogicalDecodingCtl->logical_decoding_enabled && + LogicalDecodingCtl->status_generation == generation; + LWLockRelease(LogicalDecodingControlLock); + + return matches; +} + /* * Returns true if logical WAL logging is enabled based on the shared memory * status. @@ -421,6 +456,7 @@ EnableLogicalDecoding(void) * first. */ LogicalDecodingCtl->logical_decoding_enabled = true; + LogicalDecodingCtl->status_generation++; if (!in_recovery) write_logical_decoding_status_update_record(true); @@ -558,6 +594,8 @@ DisableLogicalDecoding(void) * processes WAL records with insufficient information. */ LogicalDecodingCtl->logical_decoding_enabled = false; + if (was_enabled) + LogicalDecodingCtl->status_generation++; /* Write the WAL to disable logical decoding on standbys too */ if (!in_recovery && was_enabled) @@ -653,6 +691,7 @@ UpdateLogicalDecodingStatusEndOfRecovery(void) */ LogicalDecodingCtl->xlog_logical_info = new_status; LogicalDecodingCtl->logical_decoding_enabled = new_status; + LogicalDecodingCtl->status_generation++; elog(DEBUG1, "update logical decoding status to %d at the end of recovery", diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index c184cdf1c1..22b486e21a 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -177,6 +177,9 @@ typedef struct RemoteSlot /* RS_INVAL_NONE if valid, or the reason of invalidation */ ReplicationSlotInvalidationCause invalidated; + + /* Local logical decoding status when this slot was fetched */ + uint64 logical_decoding_generation; } RemoteSlot; static void slotsync_failure_callback(int code, Datum arg); @@ -722,25 +725,23 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, * before persisting it. This way, even if the status change record is * replayed after this check, the replay will invalidate our slot. * - * If the check fails, we keep the temporary slot and let the caller - * retry; the next cycle fetches the remote slot information again and - * will drop this slot as the remote slot no longer exists. - * - * XXX: this check cannot detect the case where logical decoding is - * already re-enabled by a slot creation on the primary at this point. - * Detecting that would require comparing the slot's restart_lsn with the - * LSN at which logical decoding was last enabled. + * If the check fails, drop the temporary slot and let the caller retry. + * The next cycle fetches the remote slot information again, which is + * necessary if logical decoding was disabled and then re-enabled in the + * meantime. */ - if (!IsLogicalDecodingEnabled()) + if (!LogicalDecodingStatusMatches(remote_slot->logical_decoding_generation)) { ereport(LOG, errmsg("could not synchronize replication slot \"%s\"", remote_slot->name), - errdetail("Logical decoding was concurrently disabled.")); + errdetail("Logical decoding status changed concurrently.")); if (slot_persistence_pending) *slot_persistence_pending = true; + ReplicationSlotDropAcquired(false); + return false; } @@ -922,7 +923,8 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, slot_updated = true; } - ReplicationSlotRelease(); + if (MyReplicationSlot) + ReplicationSlotRelease(); return slot_updated; } @@ -947,6 +949,10 @@ fetch_remote_slots(WalReceiverConn *wrconn, List *slot_names) TupleTableSlot *tupslot; List *remote_slot_list = NIL; StringInfoData query; + uint64 logical_decoding_generation; + + /* Detect status changes while fetching and synchronizing these slots. */ + logical_decoding_generation = GetLogicalDecodingStatusGeneration(); initStringInfo(&query); appendStringInfoString(&query, @@ -993,6 +999,9 @@ fetch_remote_slots(WalReceiverConn *wrconn, List *slot_names) Datum d; int col = 0; + remote_slot->logical_decoding_generation = + logical_decoding_generation; + remote_slot->name = TextDatumGetCString(slot_getattr(tupslot, ++col, &isnull)); Assert(!isnull); diff --git a/src/include/replication/logicalctl.h b/src/include/replication/logicalctl.h index 0bc1302f13..5befdd18d6 100644 --- a/src/include/replication/logicalctl.h +++ b/src/include/replication/logicalctl.h @@ -18,6 +18,8 @@ extern void StartupLogicalDecodingStatus(bool last_status); extern void InitializeProcessXLogLogicalInfo(void); extern bool ProcessBarrierUpdateXLogLogicalInfo(void); extern bool IsLogicalDecodingEnabled(void); +extern uint64 GetLogicalDecodingStatusGeneration(void); +extern bool LogicalDecodingStatusMatches(uint64 generation); extern bool IsXLogLogicalInfoEnabled(void); extern void AtEOXact_LogicalCtl(void); extern void EnsureLogicalDecodingEnabled(void); diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index 72113c5ac6..5a82677a6e 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -65,6 +65,7 @@ tests += { 't/054_unlogged_sequence_promotion.pl', 't/055_cascade_reconnect.pl', 't/056_standby_snapshot_export.pl', + 't/057_slotsync_wal_level.pl', ], }, } diff --git a/src/test/recovery/t/057_slotsync_wal_level.pl b/src/test/recovery/t/057_slotsync_wal_level.pl new file mode 100644 index 0000000000..ce1ff65f3c --- /dev/null +++ b/src/test/recovery/t/057_slotsync_wal_level.pl @@ -0,0 +1,98 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +plan skip_all => 'injection points not enabled' + unless $ENV{enable_injection_points} eq 'yes'; + +my $primary = PostgreSQL::Test::Cluster->new('primary'); +$primary->init(allows_streaming => 1); +$primary->append_conf('postgresql.conf', qq[ +autovacuum = off +log_min_messages = debug1 +]); +$primary->start; +$primary->safe_psql('postgres', q[ +create extension injection_points; +select pg_create_physical_replication_slot('phys_slot'); +]); +$primary->backup('backup'); + +my $standby = PostgreSQL::Test::Cluster->new('standby'); +$standby->init_from_backup($primary, 'backup', has_streaming => 1); +my $connstr = $primary->connstr; +$standby->append_conf('postgresql.conf', qq[ +primary_slot_name = 'phys_slot' +primary_conninfo = '$connstr dbname=postgres' +hot_standby_feedback = on +]); +$standby->start; + +$primary->safe_psql('postgres', q[ +select pg_create_logical_replication_slot( + 'sync_slot', 'test_decoding', false, false, true) +]); +my $old_restart_lsn = $primary->safe_psql('postgres', + q[select restart_lsn from pg_replication_slots where slot_name = 'sync_slot']); +$primary->wait_for_replay_catchup($standby); +is($standby->safe_psql('postgres', q[show effective_wal_level]), + 'logical', 'standby replayed activation'); + +my $sync = $standby->background_psql('postgres'); +$sync->query_until(qr/sync_started/, q(\echo sync_started +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); +$standby->wait_for_event('client backend', + 'replication-slot-create-begin'); +pass('slot sync fetched the first incarnation'); + +$primary->safe_psql('postgres', + q[select pg_drop_replication_slot('sync_slot')]); +$primary->poll_query_until('postgres', + q[select current_setting('effective_wal_level') = 'replica']) + or die 'timed out waiting for deactivation'; +$primary->wait_for_replay_catchup($standby); +is($standby->safe_psql('postgres', q[show effective_wal_level]), + 'replica', 'standby replayed deactivation'); + +$primary->safe_psql('postgres', q[ +select pg_create_logical_replication_slot( + 'sync_slot', 'test_decoding', false, false, true) +]); +my $new_restart_lsn = $primary->safe_psql('postgres', + q[select restart_lsn from pg_replication_slots where slot_name = 'sync_slot']); +isnt($new_restart_lsn, $old_restart_lsn, + 'second incarnation has a different restart LSN'); +$primary->wait_for_replay_catchup($standby); +is($standby->safe_psql('postgres', q[show effective_wal_level]), + 'logical', 'standby replayed reactivation'); + +$standby->safe_psql('postgres', q[ +select injection_points_detach('replication-slot-create-begin'); +select injection_points_wakeup('replication-slot-create-begin') +]); +$sync->quit; + +is($standby->safe_psql('postgres', + qq[select synced, temporary, invalidation_reason is null, + restart_lsn >= '$new_restart_lsn'::pg_lsn + from pg_replication_slots where slot_name = 'sync_slot']), + 't|f|t|t', 'slot was refetched before it was persisted'); + +$standby->promote; +my ($ret, $stdout, $stderr) = $standby->psql('postgres', + q[select * from pg_logical_slot_peek_changes('sync_slot', null, null)]); +is($ret, 0, 'decoding the refetched slot succeeds'); +unlike($stderr, qr/unexpected logical decoding status change/, + 'decoding does not reach a status change record'); + +$standby->stop; +$primary->stop; + +done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-22 20:15  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Nikolay Samokhvalov <nik@postgres.ai>
  0 siblings, 2 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-09-22 20:15 UTC (permalink / raw)
  To: Nikolay Samokhvalov <nik@postgres.ai>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov <nik@postgres.ai> wrote:
>
> On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> <sawada.mshk@gmail.com> wrote:
> > For slot synchronization, the local slot could be created and
> > persisted based on the remote slot information fetched before the
> > deactivation was replayed, leaving a valid slot whose restart_lsn
> > precedes the deactivation. Decoding such a slot after a failover fails
> > with:
> >
> > ERROR: unexpected logical decoding status change 0
> >
> > These races are confined to the narrow window between checking the
> > logical decoding status and the new slot becoming visible; once the
> > slot is visible, the invalidation performed by the deactivation
> > already covers it. So the fix is simple: re-check the logical decoding
> > status after the new slot becomes visible. Regular slot creation
> > raises an error and slot synchronization skips persisting the slot. If
> > the deactivation happens after the recheck instead, it is guaranteed
> > to invalidate the now-visible slot as usual. The attached 0002
> > implements this.
>
> The disable/re-enable case described in the comment above the final
> IsLogicalDecodingEnabled() check in update_and_persist_local_synced_slot() is
> reachable.
>
> On b73d13c3, the reproducer uses this sequence:
>
> 1. Slot sync fetches failover slot S and pauses at
> replication-slot-create-begin, before creating the local slot.
> 2. The primary drops S. The standby replays the logical-decoding
> deactivation while no local S exists to invalidate.
> 3. The primary recreates S. The standby replays the reactivation.
> 4. The old slot sync resumes with the first incarnation's restart_lsn.
>
> The final IsLogicalDecodingEnabled() check now returns true, so the old slot
> information is persisted. After promoting the standby, decoding that slot
> fails with:
>
> ERROR: unexpected logical decoding status change 0

Thank you for the report. Yes, while the window is very short in
practice, it indeed happens if the logical decoding is disabled and
re-enabled (by dropping and creating the same name failover slot)
between the slotsync worker fetches the slot information and creates
it.

It actually hits my concern mentioned in the comment in
update_and_persist_local_synced_slot():

     * XXX: this check cannot detect the case where logical decoding is
     * already re-enabled by a slot creation on the primary at this point.
     * Detecting that would require comparing the slot's restart_lsn with the
     * LSN at which logical decoding was last enabled.

> The attached patch adds a logical-decoding status generation. Slot sync
> records it before fetching remote slot information and refuses to persist a
> new slot if the generation changed in the meantime. It drops the temporary
> slot so that the next attempt fetches the current incarnation.

 Thank you for the patch.

An alternative approach that I think is better is to have the LSN of
the last replayed status change record in LogicalDecodingCtlData, and
check if logical decoding has been enabled since the remote slot's
restart_lsn. That's simpler than the proposed approach as we don't
need to increment the generation counter at both activation and
deactivation (which is not necessary outside recovery), nor to add
logical_decoding_generation to RemoteSlot. It also checks what we
actually need, that is, whether the WAL from the restart_lsn can be
decoded, rather than whether the status changed while synchronizing
slots.

Also, I think it's better to move the check to right after
ReplicationSlotCreate() in synchronize_one_slot() because (1) it can
simplify the code flow as we don't need to care about the slot dropped
in update_and_persist_local_synced_slot(), (2) it can save the WAL
reservation and the xmin_horizon computation, and (3) IIUC with the
proposed patch, the check can be bypassed when
update_and_persist_local_synced_slot() returns early due to
slotsync_skip_reason, leaving a temporary slot with the stale
restart_lsn. Once the slot passes the check right after its creation,
a later deactivation invalidates the slot, so we don't need to check
it again before persisting the slot.

I've attached the patch.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments:

v1-0001-Fix-slotsync-when-logical-decoding-is-disabled-an.patch (text/x-patch, 13.9K) download From 2e8b87416042b2612b8bb930b4dbc6c7cb8c8155 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Tue, 22 Sep 2026 10:40:46 -0700 Subject: [PATCH v1] Fix slotsync when logical decoding is disabled and re-enabled. Commit 6aba42c660c made slot synchronization skip persisting a new slot if logical decoding got disabled after the remote slot information was fetched. As noted in its XXX comment, the check missed the case where the last logical slot on the primary is dropped and re-created with the same name in the meantime. If the standby had replayed both the deactivation and the re-activation by then, the slot was persisted with a restart_lsn preceding the deactivation. Subsequent synchronization cycles failed with "unexpected logical decoding status change" when advancing the slot, which also stopped the synchronization of all other failover slots, and the slot could not be decoded after promotion. Fix this by remembering the end LSN of the last replayed XLOG_LOGICAL_DECODING_STATUS_CHANGE record, and by requiring the remote restart_lsn to be at or after it right after creating the local slot. Once the slot exists, a later deactivation invalidates it, so remove the check before persisting the slot. We compare the remote restart_lsn rather than the local one, so we may drop a slot that would have been usable, but the retry in the next synchronization cycle fetches fresh information. Reported-by: Nik Samokhvalov <nik@postgres.ai> Reviewed-by: Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/access/transam/xlog.c | 1 + src/backend/replication/logical/logicalctl.c | 50 +++++++++++ src/backend/replication/logical/slotsync.c | 83 +++++++++++-------- src/include/replication/logicalctl.h | 4 + .../recovery/t/051_effective_wal_level.pl | 79 ++++++++++++++++++ 5 files changed, 182 insertions(+), 35 deletions(-) diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index 9ec0be77ca0..894cb83915d 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -9648,6 +9648,7 @@ xlog_redo(XLogReaderState *record) * disabling logical decoding because logical decoding cannot process * subsequent WAL records, which may not contain logical information. */ + SetLogicalDecodingStatusChangeLSN(record->EndRecPtr); if (status) EnableLogicalDecoding(); else diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 642d965bd1c..d540763220c 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -95,6 +95,13 @@ typedef struct LogicalDecodingCtlData /* True if logical decoding might need to be disabled */ bool pending_disable; + + /* + * End LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record + * replayed, or InvalidXLogRecPtr if none has been replayed since the + * server started. Only maintained during recovery. + */ + XLogRecPtr status_change_end_lsn; } LogicalDecodingCtlData; static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; @@ -210,6 +217,49 @@ IsLogicalDecodingEnabled(void) return enabled; } +/* + * Return true if logical decoding is enabled and the given lsn is at or after + * the end of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record that enabled it + * last. This means that WAL from the lsn onward was written with logical + * decoding enabled. + * + * Note that status_change_end_lsn lives only in shared memory and is updated + * only by WAL replay, so this is accurate only during recovery and for an lsn + * at or after the point where WAL replay started in this server run. For an + * older lsn, this returns the same result as IsLogicalDecodingEnabled() if no + * status change record has been replayed yet, and false otherwise. + */ +bool +IsLogicalDecodingEnabledSince(XLogRecPtr lsn) +{ + bool result; + + LWLockAcquire(LogicalDecodingControlLock, LW_SHARED); + result = LogicalDecodingCtl->logical_decoding_enabled && + lsn >= LogicalDecodingCtl->status_change_end_lsn; + LWLockRelease(LogicalDecodingControlLock); + + return result; +} + +/* + * Remember the end LSN of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record + * being replayed. + * + * This must be called before the record changes the status, so that + * IsLogicalDecodingEnabledSince() never sees the new status paired with the + * LSN of an older record. + */ +void +SetLogicalDecodingStatusChangeLSN(XLogRecPtr lsn) +{ + Assert(RecoveryInProgress()); + + LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + LogicalDecodingCtl->status_change_end_lsn = lsn; + LWLockRelease(LogicalDecodingControlLock); +} + /* * Returns true if logical WAL logging is enabled based on the shared memory * status. diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index c0403893e23..b12d3e0f458 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -718,41 +718,6 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } - /* - * Do not persist the slot if logical decoding got disabled concurrently. - * This can happen if the last logical slot on the primary was dropped and - * the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was - * replayed after we fetched the remote slot information: WAL records - * following the slot's restart_lsn might lack the information required by - * logical decoding, and the slot invalidation performed when replaying - * the record could not find our slot as it was not created yet. - * - * It is important to perform this check after creating the slot and - * before persisting it. This way, even if the status change record is - * replayed after this check, the replay will invalidate our slot. - * - * If the check fails, we keep the temporary slot and let the caller - * retry; the next cycle fetches the remote slot information again and - * will drop this slot as the remote slot no longer exists. - * - * XXX: this check cannot detect the case where logical decoding is - * already re-enabled by a slot creation on the primary at this point. - * Detecting that would require comparing the slot's restart_lsn with the - * LSN at which logical decoding was last enabled. - */ - if (!IsLogicalDecodingEnabled()) - { - ereport(LOG, - errmsg("could not synchronize replication slot \"%s\"", - remote_slot->name), - errdetail("Logical decoding was concurrently disabled.")); - - if (slot_persistence_pending) - *slot_persistence_pending = true; - - return false; - } - ReplicationSlotPersist(); ereport(LOG, @@ -901,6 +866,54 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, remote_slot->failover, true); + /* + * The remote slot information might predate an + * XLOG_LOGICAL_DECODING_STATUS_CHANGE record that was replayed before + * our slot was created. This happens if the last logical slot on the + * primary was dropped, and possibly re-created with the same name, + * after we fetched the remote slot information. The slot invalidation + * performed when replaying the record could not find our slot, and + * WAL records following the remote restart_lsn might lack the + * information required by logical decoding. Checking only whether + * logical decoding is enabled is not enough since it might have been + * disabled and enabled again in the meantime. + * + * IsLogicalDecodingEnabledSince() knows only about the status changes + * replayed in this server run; if none has been replayed, it gives + * the same result as IsLogicalDecodingEnabled(). That's enough here + * because what we need to detect is a status change written by the + * primary after we fetched the remote slot information, which is + * always replayed in this server run. Status changes written before + * the fetch don't matter, as the primary writes a deactivation record + * only when it has no valid logical slot: the remote restart_lsn is + * always past such a record and the following activation record. + * + * It is important to perform this check after creating the slot. If a + * status change record is replayed after this check, the replay + * invalidates our slot. So once a slot passes this check, its + * restart_lsn stays decodable until it is invalidated, and we don't + * need to check it again before persisting the slot. + * + * If the check fails, drop the slot and let the caller retry; the + * next cycle fetches the remote slot information again. We cannot + * keep the slot as it would continue to use the stale restart_lsn. + */ + if (!IsLogicalDecodingEnabledSince(remote_slot->restart_lsn)) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding on the standby has not been continuously enabled since the remote slot's restart LSN %X/%08X.", + LSN_FORMAT_ARGS(remote_slot->restart_lsn))); + + ReplicationSlotDropAcquired(false); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + /* For shorter lines. */ slot = MyReplicationSlot; diff --git a/src/include/replication/logicalctl.h b/src/include/replication/logicalctl.h index 0bc1302f130..73333e133e2 100644 --- a/src/include/replication/logicalctl.h +++ b/src/include/replication/logicalctl.h @@ -14,10 +14,14 @@ #ifndef LOGICALCTL_H #define LOGICALCTL_H +#include "access/xlogdefs.h" + extern void StartupLogicalDecodingStatus(bool last_status); extern void InitializeProcessXLogLogicalInfo(void); extern bool ProcessBarrierUpdateXLogLogicalInfo(void); extern bool IsLogicalDecodingEnabled(void); +extern bool IsLogicalDecodingEnabledSince(XLogRecPtr lsn); +extern void SetLogicalDecodingStatusChangeLSN(XLogRecPtr lsn); extern bool IsXLogLogicalInfoEnabled(void); extern void AtEOXact_LogicalCtl(void); extern void EnsureLogicalDecodingEnabled(void); diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index b11690863d9..6ca7e273542 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -598,6 +598,85 @@ select pg_sync_replication_slots(); '0', "no synced slot is left behind on standby5"); + # Test the same race, but where the slot is re-created on the primary + # before the slot synchronization resumes. Logical decoding is enabled + # again at the time the local slot is created, so checking the logical + # decoding status alone cannot tell that the remote slot information + # predates the deactivation. + + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5 for the re-creation test" + ); + + $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + + # Drop and re-create the slot, and wait for the standby to replay both + # the deactivation and the activation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + my $restart_lsn = $primary->safe_psql('postgres', + qq[select restart_lsn from pg_replication_slots where slot_name = 'sync_slot'] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got deactivated and activated again on standby5"); + + # Resume the slot synchronization. It must drop the slot created from + # the stale information, and re-create it from the re-created remote slot + # on retry. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql( + 'postgres', qq[ +select injection_points_detach('replication-slot-create-begin'); +select injection_points_wakeup('replication-slot-create-begin'); +]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot".*\n.*DETAIL: Logical decoding on the standby has not been continuously enabled since the remote slot's restart LSN/, + $log_offset); + $standby5->poll_query_until('postgres', + qq[select restart_lsn >= '$restart_lsn' from pg_replication_slots where slot_name = 'sync_slot'] + ) + or die + "timed out waiting for the slot to be re-created from the re-created remote slot"; + + # The slot created on retry might not be persisted until the remote slot + # catches up with the catalog_xmin computed locally. Drop the remote slot + # to let the slot synchronization finish, keeping logical decoding enabled + # with another slot as the slot synchronization requires it. + $primary->safe_psql( + 'postgres', qq[ +select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); +select pg_drop_replication_slot('sync_slot'); +]); + $primary->wait_for_replay_catchup($standby5); + $psql_sync_slot->quit; + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot4')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5 after the re-creation test" + ); + # Test that logical slot creation on a standby fails cleanly if logical # decoding is concurrently deactivated by the end-of-recovery transition # upon promotion. -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-24 09:19  shveta malik <shveta.malik@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 1 reply; 59+ messages in thread

From: shveta malik @ 2026-09-24 09:19 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers; shveta malik <shveta.malik@gmail.com>

On Wed, Sep 23, 2026 at 1:46 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov <nik@postgres.ai> wrote:
> >
> > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> > <sawada.mshk@gmail.com> wrote:
> > > For slot synchronization, the local slot could be created and
> > > persisted based on the remote slot information fetched before the
> > > deactivation was replayed, leaving a valid slot whose restart_lsn
> > > precedes the deactivation. Decoding such a slot after a failover fails
> > > with:
> > >
> > > ERROR: unexpected logical decoding status change 0
> > >
> > > These races are confined to the narrow window between checking the
> > > logical decoding status and the new slot becoming visible; once the
> > > slot is visible, the invalidation performed by the deactivation
> > > already covers it. So the fix is simple: re-check the logical decoding
> > > status after the new slot becomes visible. Regular slot creation
> > > raises an error and slot synchronization skips persisting the slot. If
> > > the deactivation happens after the recheck instead, it is guaranteed
> > > to invalidate the now-visible slot as usual. The attached 0002
> > > implements this.
> >
> > The disable/re-enable case described in the comment above the final
> > IsLogicalDecodingEnabled() check in update_and_persist_local_synced_slot() is
> > reachable.
> >
> > On b73d13c3, the reproducer uses this sequence:
> >
> > 1. Slot sync fetches failover slot S and pauses at
> > replication-slot-create-begin, before creating the local slot.
> > 2. The primary drops S. The standby replays the logical-decoding
> > deactivation while no local S exists to invalidate.
> > 3. The primary recreates S. The standby replays the reactivation.
> > 4. The old slot sync resumes with the first incarnation's restart_lsn.
> >
> > The final IsLogicalDecodingEnabled() check now returns true, so the old slot
> > information is persisted. After promoting the standby, decoding that slot
> > fails with:
> >
> > ERROR: unexpected logical decoding status change 0

Thank You for reporting the issue.

> Thank you for the report. Yes, while the window is very short in
> practice, it indeed happens if the logical decoding is disabled and
> re-enabled (by dropping and creating the same name failover slot)
> between the slotsync worker fetches the slot information and creates
> it.
>
> It actually hits my concern mentioned in the comment in
> update_and_persist_local_synced_slot():
>
>      * XXX: this check cannot detect the case where logical decoding is
>      * already re-enabled by a slot creation on the primary at this point.
>      * Detecting that would require comparing the slot's restart_lsn with the
>      * LSN at which logical decoding was last enabled.
>
> > The attached patch adds a logical-decoding status generation. Slot sync
> > records it before fetching remote slot information and refuses to persist a
> > new slot if the generation changed in the meantime. It drops the temporary
> > slot so that the next attempt fetches the current incarnation.
>
>  Thank you for the patch.
>
> An alternative approach that I think is better is to have the LSN of
> the last replayed status change record in LogicalDecodingCtlData, and
> check if logical decoding has been enabled since the remote slot's
> restart_lsn. That's simpler than the proposed approach as we don't
> need to increment the generation counter at both activation and
> deactivation (which is not necessary outside recovery), nor to add
> logical_decoding_generation to RemoteSlot. It also checks what we
> actually need, that is, whether the WAL from the restart_lsn can be
> decoded, rather than whether the status changed while synchronizing
> slots.

I agree.

> Also, I think it's better to move the check to right after
> ReplicationSlotCreate() in synchronize_one_slot()

I also think so.

> because (1) it can
> simplify the code flow as we don't need to care about the slot dropped
> in update_and_persist_local_synced_slot(), (2) it can save the WAL
> reservation and the xmin_horizon computation, and (3) IIUC with the
> proposed patch, the check can be bypassed when
> update_and_persist_local_synced_slot() returns early due to
> slotsync_skip_reason, leaving a temporary slot with the stale
> restart_lsn.

I agree on pt 1 and 2, need to verify 3 though.

> Once the slot passes the check right after its creation,
> a later deactivation invalidates the slot, so we don't need to check
> it again before persisting the slot.

I agree. It is not only invalidated but will be dropped too by
drop_local_obsolete_slots() at the start of the next sync-cycle.

> I've attached the patch.
>

Thanks for the  patch. I like this approach and it looks good overall.
I'm still in the process of verifying it, but here are a few comments
in the meantime:

1)
Comment atop status_change_end_lsn says "only maintained during
recovery", but after promotion the stale value stays in shared memory.
Shall we set it to InvalidXLogRecPtr in
UpdateLogicalDecodingStatusEndOfRecovery()?

2)
Shall we set status_change_end_lsn to InvalidXLogRecPtr explicitly in
StartupLogicalDecodingStatus(), before the early return for wal_level
= minimal? That makes the intention clear rather than relying on
zero-initialized shared memory.

3)
Shall we say in a comment(atop the field or/and in
IsLogicalDecodingEnabledSince()) that the new field is not persisted,
and why that is safe

4)
The comment atop SetLogicalDecodingStatusChangeLSN() says it must be
called before the record changes the status. Why don't we make the
update part of EnableLogicalDecoding() itself? Something like:

EnableLogicalDecoding(XLogRecPtr redo_end_lsn)
{
...
in_recovery = RecoveryInProgress();

/* Invalid unless called from redo */
Assert(in_recovery == XLogRecPtrIsValid(redo_end_lsn));
..
LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
...
    if (in_recovery)
LogicalDecodingCtl->last_enabled_end_lsn = redo_end_lsn;  /* same lock hold */
else
write_logical_decoding_status_update_record(true);


5)
+ ereport(LOG,
+ errmsg("could not synchronize replication slot \"%s\"",
+   remote_slot->name),
+ errdetail("Logical decoding on the standby has not been continuously
enabled since the remote slot's restart LSN %X/%08X.",
+  LSN_FORMAT_ARGS(remote_slot->restart_lsn)));

Instead of above, shall we say something like:

Logical decoding was disabled after the remote slot's restart LSN %X/%08X
Or
Logical decoding status changed after the remote slot's restart LSN %X/%08X.

6)
IsLogicalDecodingEnabledSince() is meaningful only on standby, shall
we add Assert(RecoveryInProgress())?

thanks
Shveta






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-24 11:40  Nisha Moond <nisha.moond412@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 1 reply; 59+ messages in thread

From: Nisha Moond @ 2026-09-24 11:40 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Wed, Sep 23, 2026 at 1:45 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov <nik@postgres.ai> wrote:
> >
> > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> > <sawada.mshk@gmail.com> wrote:
> > > For slot synchronization, the local slot could be created and
> > > persisted based on the remote slot information fetched before the
> > > deactivation was replayed, leaving a valid slot whose restart_lsn
> > > precedes the deactivation. Decoding such a slot after a failover fails
> > > with:
> > >
> > > ERROR: unexpected logical decoding status change 0
> > >
> > > These races are confined to the narrow window between checking the
> > > logical decoding status and the new slot becoming visible; once the
> > > slot is visible, the invalidation performed by the deactivation
> > > already covers it. So the fix is simple: re-check the logical decoding
> > > status after the new slot becomes visible. Regular slot creation
> > > raises an error and slot synchronization skips persisting the slot. If
> > > the deactivation happens after the recheck instead, it is guaranteed
> > > to invalidate the now-visible slot as usual. The attached 0002
> > > implements this.
> >
> > The disable/re-enable case described in the comment above the final
> > IsLogicalDecodingEnabled() check in update_and_persist_local_synced_slot() is
> > reachable.
> >
> > On b73d13c3, the reproducer uses this sequence:
> >
> > 1. Slot sync fetches failover slot S and pauses at
> > replication-slot-create-begin, before creating the local slot.
> > 2. The primary drops S. The standby replays the logical-decoding
> > deactivation while no local S exists to invalidate.
> > 3. The primary recreates S. The standby replays the reactivation.
> > 4. The old slot sync resumes with the first incarnation's restart_lsn.
> >
> > The final IsLogicalDecodingEnabled() check now returns true, so the old slot
> > information is persisted. After promoting the standby, decoding that slot
> > fails with:
> >
> > ERROR: unexpected logical decoding status change 0
>
> Thank you for the report. Yes, while the window is very short in
> practice, it indeed happens if the logical decoding is disabled and
> re-enabled (by dropping and creating the same name failover slot)
> between the slotsync worker fetches the slot information and creates
> it.
>
> It actually hits my concern mentioned in the comment in
> update_and_persist_local_synced_slot():
>
>      * XXX: this check cannot detect the case where logical decoding is
>      * already re-enabled by a slot creation on the primary at this point.
>      * Detecting that would require comparing the slot's restart_lsn with the
>      * LSN at which logical decoding was last enabled.
>
> > The attached patch adds a logical-decoding status generation. Slot sync
> > records it before fetching remote slot information and refuses to persist a
> > new slot if the generation changed in the meantime. It drops the temporary
> > slot so that the next attempt fetches the current incarnation.
>
>  Thank you for the patch.
>
> An alternative approach that I think is better is to have the LSN of
> the last replayed status change record in LogicalDecodingCtlData, and
> check if logical decoding has been enabled since the remote slot's
> restart_lsn. That's simpler than the proposed approach as we don't
> need to increment the generation counter at both activation and
> deactivation (which is not necessary outside recovery), nor to add
> logical_decoding_generation to RemoteSlot. It also checks what we
> actually need, that is, whether the WAL from the restart_lsn can be
> decoded, rather than whether the status changed while synchronizing
> slots.
>
> Also, I think it's better to move the check to right after
> ReplicationSlotCreate() in synchronize_one_slot() because (1) it can
> simplify the code flow as we don't need to care about the slot dropped
> in update_and_persist_local_synced_slot(), (2) it can save the WAL
> reservation and the xmin_horizon computation, and (3) IIUC with the
> proposed patch, the check can be bypassed when
> update_and_persist_local_synced_slot() returns early due to
> slotsync_skip_reason, leaving a temporary slot with the stale
> restart_lsn. Once the slot passes the check right after its creation,
> a later deactivation invalidates the slot, so we don't need to check
> it again before persisting the slot.
>
> I've attached the patch.
>

I tested the patch and it fixes the problem. I found no critical
issues. A couple of comments:
1) Now that a newly created synced slot is dropped on a failed new
check rather than kept as RS_TEMPORARY, a standby that is lagging in
replay can end up creating and dropping the slot on every sync cycle.
For example, replay is paused with pg_wal_replay_pause() or
recovery_min_apply_delay is large. After the primary turns logical
decoding off and then on again, the standby receives the activation
record but doesn't replay it. Meanwhile the slotsync worker keeps
fetching the failover slot, creates it, fails the new
IsLogicalDecodingEnabledSince() check, and drops it. This repeats
every cycle until the record is replayed.

Each cycle creates the slot on disk and a pgstat entry, then removes
both again. I think this can be avoided with a cheaper pre-check,
IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
ReplicationSlotCreate().

Thoughts?

2) The overview comment at the top of slotsync.c explains each reason
a slot isn't synced yet, but it doesn't mention this new
drop-and-retry case. Should we add it there too?

--
Thanks,
Nisha






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-24 20:29  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-09-24 20:29 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Sep 24, 2026 at 2:19 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Wed, Sep 23, 2026 at 1:46 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov <nik@postgres.ai> wrote:
> > >
> > > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> > > <sawada.mshk@gmail.com> wrote:
> > > > For slot synchronization, the local slot could be created and
> > > > persisted based on the remote slot information fetched before the
> > > > deactivation was replayed, leaving a valid slot whose restart_lsn
> > > > precedes the deactivation. Decoding such a slot after a failover fails
> > > > with:
> > > >
> > > > ERROR: unexpected logical decoding status change 0
> > > >
> > > > These races are confined to the narrow window between checking the
> > > > logical decoding status and the new slot becoming visible; once the
> > > > slot is visible, the invalidation performed by the deactivation
> > > > already covers it. So the fix is simple: re-check the logical decoding
> > > > status after the new slot becomes visible. Regular slot creation
> > > > raises an error and slot synchronization skips persisting the slot. If
> > > > the deactivation happens after the recheck instead, it is guaranteed
> > > > to invalidate the now-visible slot as usual. The attached 0002
> > > > implements this.
> > >
> > > The disable/re-enable case described in the comment above the final
> > > IsLogicalDecodingEnabled() check in update_and_persist_local_synced_slot() is
> > > reachable.
> > >
> > > On b73d13c3, the reproducer uses this sequence:
> > >
> > > 1. Slot sync fetches failover slot S and pauses at
> > > replication-slot-create-begin, before creating the local slot.
> > > 2. The primary drops S. The standby replays the logical-decoding
> > > deactivation while no local S exists to invalidate.
> > > 3. The primary recreates S. The standby replays the reactivation.
> > > 4. The old slot sync resumes with the first incarnation's restart_lsn.
> > >
> > > The final IsLogicalDecodingEnabled() check now returns true, so the old slot
> > > information is persisted. After promoting the standby, decoding that slot
> > > fails with:
> > >
> > > ERROR: unexpected logical decoding status change 0
>
> Thank You for reporting the issue.
>
> > Thank you for the report. Yes, while the window is very short in
> > practice, it indeed happens if the logical decoding is disabled and
> > re-enabled (by dropping and creating the same name failover slot)
> > between the slotsync worker fetches the slot information and creates
> > it.
> >
> > It actually hits my concern mentioned in the comment in
> > update_and_persist_local_synced_slot():
> >
> >      * XXX: this check cannot detect the case where logical decoding is
> >      * already re-enabled by a slot creation on the primary at this point.
> >      * Detecting that would require comparing the slot's restart_lsn with the
> >      * LSN at which logical decoding was last enabled.
> >
> > > The attached patch adds a logical-decoding status generation. Slot sync
> > > records it before fetching remote slot information and refuses to persist a
> > > new slot if the generation changed in the meantime. It drops the temporary
> > > slot so that the next attempt fetches the current incarnation.
> >
> >  Thank you for the patch.
> >
> > An alternative approach that I think is better is to have the LSN of
> > the last replayed status change record in LogicalDecodingCtlData, and
> > check if logical decoding has been enabled since the remote slot's
> > restart_lsn. That's simpler than the proposed approach as we don't
> > need to increment the generation counter at both activation and
> > deactivation (which is not necessary outside recovery), nor to add
> > logical_decoding_generation to RemoteSlot. It also checks what we
> > actually need, that is, whether the WAL from the restart_lsn can be
> > decoded, rather than whether the status changed while synchronizing
> > slots.
>
> I agree.
>
> > Also, I think it's better to move the check to right after
> > ReplicationSlotCreate() in synchronize_one_slot()
>
> I also think so.
>
> > because (1) it can
> > simplify the code flow as we don't need to care about the slot dropped
> > in update_and_persist_local_synced_slot(), (2) it can save the WAL
> > reservation and the xmin_horizon computation, and (3) IIUC with the
> > proposed patch, the check can be bypassed when
> > update_and_persist_local_synced_slot() returns early due to
> > slotsync_skip_reason, leaving a temporary slot with the stale
> > restart_lsn.
>
> I agree on pt 1 and 2, need to verify 3 though.
>
> > Once the slot passes the check right after its creation,
> > a later deactivation invalidates the slot, so we don't need to check
> > it again before persisting the slot.
>
> I agree. It is not only invalidated but will be dropped too by
> drop_local_obsolete_slots() at the start of the next sync-cycle.
>
> > I've attached the patch.
> >
>
> Thanks for the  patch. I like this approach and it looks good overall.
> I'm still in the process of verifying it, but here are a few comments
> in the meantime:

Thank you for reviewing the patch!

> 1)
> Comment atop status_change_end_lsn says "only maintained during
> recovery", but after promotion the stale value stays in shared memory.
> Shall we set it to InvalidXLogRecPtr in
> UpdateLogicalDecodingStatusEndOfRecovery()?

Agreed.

>
> 2)
> Shall we set status_change_end_lsn to InvalidXLogRecPtr explicitly in
> StartupLogicalDecodingStatus(), before the early return for wal_level
> = minimal? That makes the intention clear rather than relying on
> zero-initialized shared memory.

Agreed.

>
> 3)
> Shall we say in a comment(atop the field or/and in
> IsLogicalDecodingEnabledSince()) that the new field is not persisted,
> and why that is safe

Okay.

>
> 4)
> The comment atop SetLogicalDecodingStatusChangeLSN() says it must be
> called before the record changes the status. Why don't we make the
> update part of EnableLogicalDecoding() itself? Something like:
>
> EnableLogicalDecoding(XLogRecPtr redo_end_lsn)
> {
> ...
> in_recovery = RecoveryInProgress();
>
> /* Invalid unless called from redo */
> Assert(in_recovery == XLogRecPtrIsValid(redo_end_lsn));
> ..
> LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
> ...
>     if (in_recovery)
> LogicalDecodingCtl->last_enabled_end_lsn = redo_end_lsn;  /* same lock hold */
> else
> write_logical_decoding_status_update_record(true);

I think that it doesn't cover the case where we replay the
STATUS_CHANGE record with logical_decoding=true while the logical
decoding is enabled. IIUC this can technically happen since we start
the recovery from a redo point but the initial logical decoding status
is based on the checkpoint record.

> 5)
> + ereport(LOG,
> + errmsg("could not synchronize replication slot \"%s\"",
> +   remote_slot->name),
> + errdetail("Logical decoding on the standby has not been continuously
> enabled since the remote slot's restart LSN %X/%08X.",
> +  LSN_FORMAT_ARGS(remote_slot->restart_lsn)));
>
> Instead of above, shall we say something like:
>
> Logical decoding was disabled after the remote slot's restart LSN %X/%08X
> Or
> Logical decoding status changed after the remote slot's restart LSN %X/%08X.

Agreed.

>
> 6)
> IsLogicalDecodingEnabledSince() is meaningful only on standby, shall
> we add Assert(RecoveryInProgress())?

Agreed.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-24 22:08  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 3 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-09-24 22:08 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Wed, Sep 23, 2026 at 1:45 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov <nik@postgres.ai> wrote:
> > >
> > > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> > > <sawada.mshk@gmail.com> wrote:
> > > > For slot synchronization, the local slot could be created and
> > > > persisted based on the remote slot information fetched before the
> > > > deactivation was replayed, leaving a valid slot whose restart_lsn
> > > > precedes the deactivation. Decoding such a slot after a failover fails
> > > > with:
> > > >
> > > > ERROR: unexpected logical decoding status change 0
> > > >
> > > > These races are confined to the narrow window between checking the
> > > > logical decoding status and the new slot becoming visible; once the
> > > > slot is visible, the invalidation performed by the deactivation
> > > > already covers it. So the fix is simple: re-check the logical decoding
> > > > status after the new slot becomes visible. Regular slot creation
> > > > raises an error and slot synchronization skips persisting the slot. If
> > > > the deactivation happens after the recheck instead, it is guaranteed
> > > > to invalidate the now-visible slot as usual. The attached 0002
> > > > implements this.
> > >
> > > The disable/re-enable case described in the comment above the final
> > > IsLogicalDecodingEnabled() check in update_and_persist_local_synced_slot() is
> > > reachable.
> > >
> > > On b73d13c3, the reproducer uses this sequence:
> > >
> > > 1. Slot sync fetches failover slot S and pauses at
> > > replication-slot-create-begin, before creating the local slot.
> > > 2. The primary drops S. The standby replays the logical-decoding
> > > deactivation while no local S exists to invalidate.
> > > 3. The primary recreates S. The standby replays the reactivation.
> > > 4. The old slot sync resumes with the first incarnation's restart_lsn.
> > >
> > > The final IsLogicalDecodingEnabled() check now returns true, so the old slot
> > > information is persisted. After promoting the standby, decoding that slot
> > > fails with:
> > >
> > > ERROR: unexpected logical decoding status change 0
> >
> > Thank you for the report. Yes, while the window is very short in
> > practice, it indeed happens if the logical decoding is disabled and
> > re-enabled (by dropping and creating the same name failover slot)
> > between the slotsync worker fetches the slot information and creates
> > it.
> >
> > It actually hits my concern mentioned in the comment in
> > update_and_persist_local_synced_slot():
> >
> >      * XXX: this check cannot detect the case where logical decoding is
> >      * already re-enabled by a slot creation on the primary at this point.
> >      * Detecting that would require comparing the slot's restart_lsn with the
> >      * LSN at which logical decoding was last enabled.
> >
> > > The attached patch adds a logical-decoding status generation. Slot sync
> > > records it before fetching remote slot information and refuses to persist a
> > > new slot if the generation changed in the meantime. It drops the temporary
> > > slot so that the next attempt fetches the current incarnation.
> >
> >  Thank you for the patch.
> >
> > An alternative approach that I think is better is to have the LSN of
> > the last replayed status change record in LogicalDecodingCtlData, and
> > check if logical decoding has been enabled since the remote slot's
> > restart_lsn. That's simpler than the proposed approach as we don't
> > need to increment the generation counter at both activation and
> > deactivation (which is not necessary outside recovery), nor to add
> > logical_decoding_generation to RemoteSlot. It also checks what we
> > actually need, that is, whether the WAL from the restart_lsn can be
> > decoded, rather than whether the status changed while synchronizing
> > slots.
> >
> > Also, I think it's better to move the check to right after
> > ReplicationSlotCreate() in synchronize_one_slot() because (1) it can
> > simplify the code flow as we don't need to care about the slot dropped
> > in update_and_persist_local_synced_slot(), (2) it can save the WAL
> > reservation and the xmin_horizon computation, and (3) IIUC with the
> > proposed patch, the check can be bypassed when
> > update_and_persist_local_synced_slot() returns early due to
> > slotsync_skip_reason, leaving a temporary slot with the stale
> > restart_lsn. Once the slot passes the check right after its creation,
> > a later deactivation invalidates the slot, so we don't need to check
> > it again before persisting the slot.
> >
> > I've attached the patch.
> >
>
> I tested the patch and it fixes the problem. I found no critical
> issues. A couple of comments:
> 1) Now that a newly created synced slot is dropped on a failed new
> check rather than kept as RS_TEMPORARY, a standby that is lagging in
> replay can end up creating and dropping the slot on every sync cycle.
> For example, replay is paused with pg_wal_replay_pause() or
> recovery_min_apply_delay is large. After the primary turns logical
> decoding off and then on again, the standby receives the activation
> record but doesn't replay it. Meanwhile the slotsync worker keeps
> fetching the failover slot, creates it, fails the new
> IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> every cycle until the record is replayed.
>
> Each cycle creates the slot on disk and a pgstat entry, then removes
> both again. I think this can be avoided with a cheaper pre-check,
> IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> ReplicationSlotCreate().
>
> Thoughts?

I agree with your analysis. I think that in this case, the logical
slot doesn't need to be dropped because WAL records after its
restart_lsn are written with logical decoding information. Thinking on
IsLogicalDecodingEnabledSince() further, I think it can work fine for
the slot only when the replay LSN >= slot's restart_lsn. If the slot's
restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
have to be recreated only in the disable/re-enable case.

>
> 2) The overview comment at the top of slotsync.c explains each reason
> a slot isn't synced yet, but it doesn't mention this new
> drop-and-retry case. Should we add it there too?

The patch describes the details of the disabled/re-enabled case in
synchronize_one_slot() and it looks sufficient to me.

I've updated the patch for the above idea. In this version, the patch
tracks only the last STATUS_CHANGE record that enables logical
decoding, which makes it easy to check if logical decoding has
continuously been enabled since the remote slot's restart_lsn.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments:

v2-0001-Fix-slotsync-when-logical-decoding-is-disabled-an.patch (text/x-patch, 15.6K) download From adc7db5f52acc35115ea68969365a5ba64eff525 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Tue, 22 Sep 2026 10:40:46 -0700 Subject: [PATCH v2] Fix slotsync when logical decoding is disabled and re-enabled. Commit 6aba42c660c made slot synchronization skip persisting a new slot if logical decoding got disabled after the remote slot information was fetched. As noted in its XXX comment, the check missed the case where the last logical slot on the primary is dropped and re-created with the same name in the meantime. If the standby had replayed both the deactivation and the re-activation by then, the slot was persisted with a restart_lsn preceding the deactivation. Subsequent synchronization cycles failed with "unexpected logical decoding status change" when advancing the slot, which also stopped the synchronization of all other failover slots, and the slot could not be decoded after promotion. Fix this by remembering the end LSN of the last replayed XLOG_LOGICAL_DECODING_STATUS_CHANGE record that enabled logical decoding, and checking the remote restart_lsn against it right after the local slot is created. The check runs only once the standby has replayed the remote restart_lsn, as nothing can be said about WAL it hasn't replayed yet. We compare the remote restart_lsn rather than the local one, so we may drop a slot that would have been usable, but the next synchronization cycle fetches fresh information. Reported-by: Nik Samokhvalov <nik@postgres.ai> Reviewed-by: shveta malik <shveta.malik@gmail.com> Reviewed-by: Nisha Moond <nisha.moond412@gmail.com> Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/access/transam/xlog.c | 2 +- src/backend/replication/logical/logicalctl.c | 65 ++++++++++++++- src/backend/replication/logical/slotsync.c | 82 +++++++++++-------- src/include/replication/logicalctl.h | 5 +- .../recovery/t/051_effective_wal_level.pl | 79 ++++++++++++++++++ 5 files changed, 194 insertions(+), 39 deletions(-) diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index 7b38c167eac..d8ac785b1f4 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -8782,7 +8782,7 @@ xlog_redo(XLogReaderState *record) * subsequent WAL records, which may not contain logical information. */ if (status) - EnableLogicalDecoding(); + EnableLogicalDecoding(lsn); else DisableLogicalDecoding(); diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index e5340880fa7..a2bef0aaa80 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -64,6 +64,7 @@ #include "postgres.h" #include "access/xloginsert.h" +#include "access/xlogrecovery.h" #include "catalog/pg_control.h" #include "miscadmin.h" #include "replication/slot.h" @@ -95,6 +96,22 @@ typedef struct LogicalDecodingCtlData /* True if logical decoding might need to be disabled */ bool pending_disable; + + /* + * End LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record that + * enabled logical decoding, or InvalidXLogRecPtr if none has been + * replayed since the server started. Checking it with + * logical_decoding_enabled tells from which point on WAL was written with + * logical decoding enabled; see StandbyLogicalDecodingEnabledSince(). + * + * WAL records that disable logical decoding are deliberately not tracked + * here. logical_decoding_enabled is false while decoding is off, which is + * all the check needs. + * + * This is maintained only during recovery and is not persisted, so it + * says nothing about a status change replayed in an earlier server run. + */ + XLogRecPtr last_replayed_enable_lsn; } LogicalDecodingCtlData; static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; @@ -210,6 +227,35 @@ IsLogicalDecodingEnabled(void) return enabled; } +/* + * Return true if logical decoding has been enabled continuously from the given + * LSN up to the current replay position, that is, if the WAL in that range + * was written with logical decoding enabled. + * + * The given LSN must have been replayed already; nothing can be said about + * WAL this server has not replayed yet. The caller is responsible for checking + * that. + * + * A true result therefore covers only the WAL replayed so far. A deactivation + * replayed after the call still applies, and callers must arrange for that + * themselves. + */ +bool +StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn) +{ + bool result; + + Assert(RecoveryInProgress()); + Assert(lsn <= GetXLogReplayRecPtr(NULL)); + + LWLockAcquire(LogicalDecodingControlLock, LW_SHARED); + result = LogicalDecodingCtl->logical_decoding_enabled && + lsn >= LogicalDecodingCtl->last_replayed_enable_lsn; + LWLockRelease(LogicalDecodingControlLock); + + return result; +} + /* * Returns true if logical WAL logging is enabled based on the shared memory * status. @@ -330,21 +376,36 @@ EnsureLogicalDecodingEnabled(void) */ PG_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); { - EnableLogicalDecoding(); + EnableLogicalDecoding(InvalidXLogRecPtr); } PG_END_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); } /* * A workhorse function to enable logical decoding. + * + * lsn is the end LSN of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record + * being replayed, and is InvalidXLogRecPtr when not called from redo. */ void -EnableLogicalDecoding(void) +EnableLogicalDecoding(XLogRecPtr lsn) { bool in_recovery; LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Remember where logical decoding was enabled. This has to happen before + * the early return below, because replay can reach here with the status + * already on. For example, CreateCheckPoint() fixes the redo point before + * it records logicalDecodingEnabled, so a checkpoint can claim logical + * decoding is enabled while the record that enabled it still follows the + * redo point. + */ + Assert(RecoveryInProgress() == XLogRecPtrIsValid(lsn)); + if (XLogRecPtrIsValid(lsn)) + LogicalDecodingCtl->last_replayed_enable_lsn = lsn; + /* Return if it is already enabled */ if (LogicalDecodingCtl->logical_decoding_enabled) { diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index c184cdf1c17..4c40278f573 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -709,41 +709,6 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } - /* - * Do not persist the slot if logical decoding got disabled concurrently. - * This can happen if the last logical slot on the primary was dropped and - * the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was - * replayed after we fetched the remote slot information: WAL records - * following the slot's restart_lsn might lack the information required by - * logical decoding, and the slot invalidation performed when replaying - * the record could not find our slot as it was not created yet. - * - * It is important to perform this check after creating the slot and - * before persisting it. This way, even if the status change record is - * replayed after this check, the replay will invalidate our slot. - * - * If the check fails, we keep the temporary slot and let the caller - * retry; the next cycle fetches the remote slot information again and - * will drop this slot as the remote slot no longer exists. - * - * XXX: this check cannot detect the case where logical decoding is - * already re-enabled by a slot creation on the primary at this point. - * Detecting that would require comparing the slot's restart_lsn with the - * LSN at which logical decoding was last enabled. - */ - if (!IsLogicalDecodingEnabled()) - { - ereport(LOG, - errmsg("could not synchronize replication slot \"%s\"", - remote_slot->name), - errdetail("Logical decoding was concurrently disabled.")); - - if (slot_persistence_pending) - *slot_persistence_pending = true; - - return false; - } - ReplicationSlotPersist(); ereport(LOG, @@ -874,6 +839,7 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, { NameData plugin_name; TransactionId xmin_horizon = InvalidTransactionId; + XLogRecPtr replay_lsn; /* Skip creating the local slot if remote_slot is invalidated already */ if (remote_slot->invalidated != RS_INVAL_NONE) @@ -892,6 +858,52 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, remote_slot->failover, true); + /* + * The remote slot information can predate a status change record that + * this standby has already replayed. That happens when the last + * logical slot on the primary is dropped, and possibly re-created + * with the same name, after fetch_remote_slots() ran: the + * deactivation could not invalidate our slot because it did not exist + * yet, and WAL following the remote restart_lsn may lack the + * information logical decoding needs. Checking only whether logical + * decoding is enabled is not enough, as it can have been disabled and + * enabled again in the meantime. + * + * The check has to come after ReplicationSlotCreate(), which makes + * the slot both visible and acquired. A deactivation replayed from + * here on finds the slot in InvalidatePossiblyObsoleteSlot(), signals + * a recovery conflict and waits for the slot to be released before + * invalidating it, so replay cannot get past that record behind our + * back. That is also why the status needs no recheck before the slot + * is persisted. (The invalidation is performed only in hot standby, + * which slot synchronization requires anyway.) + * + * WAL beyond the replay position tells us nothing, so a remote + * restart_lsn past it is accepted and left to the interlock above. + * + * The comparison uses the remote restart_lsn rather than the local + * one, so a slot that would have been usable may be dropped; the next + * cycle fetches fresh information. The slot cannot be kept, as it + * would go on using the stale restart_lsn. + */ + replay_lsn = GetXLogReplayRecPtr(NULL); + if (remote_slot->restart_lsn <= replay_lsn && + !StandbyLogicalDecodingEnabledSince(remote_slot->restart_lsn)) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding was disabled after the remote slot's restart LSN %X/%08X.", + LSN_FORMAT_ARGS(remote_slot->restart_lsn))); + + ReplicationSlotDropAcquired(false); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + /* For shorter lines. */ slot = MyReplicationSlot; diff --git a/src/include/replication/logicalctl.h b/src/include/replication/logicalctl.h index 0bc1302f130..97cacb02e4e 100644 --- a/src/include/replication/logicalctl.h +++ b/src/include/replication/logicalctl.h @@ -14,14 +14,17 @@ #ifndef LOGICALCTL_H #define LOGICALCTL_H +#include "access/xlogdefs.h" + extern void StartupLogicalDecodingStatus(bool last_status); extern void InitializeProcessXLogLogicalInfo(void); extern bool ProcessBarrierUpdateXLogLogicalInfo(void); extern bool IsLogicalDecodingEnabled(void); +extern bool StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn); extern bool IsXLogLogicalInfoEnabled(void); extern void AtEOXact_LogicalCtl(void); extern void EnsureLogicalDecodingEnabled(void); -extern void EnableLogicalDecoding(void); +extern void EnableLogicalDecoding(XLogRecPtr lsn); extern void RequestDisableLogicalDecoding(void); extern void DisableLogicalDecodingIfNecessary(void); extern void DisableLogicalDecoding(void); diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 401a67ad1a6..c02cde6b2ce 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -597,6 +597,85 @@ select pg_sync_replication_slots(); '0', "no synced slot is left behind on standby5"); + # Test the same race, but where the slot is re-created on the primary + # before the slot synchronization resumes. Logical decoding is enabled + # again at the time the local slot is created, so checking the logical + # decoding status alone cannot tell that the remote slot information + # predates the deactivation. + + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5 for the re-creation test" + ); + + $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + + # Drop and re-create the slot, and wait for the standby to replay both + # the deactivation and the activation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + my $restart_lsn = $primary->safe_psql('postgres', + qq[select restart_lsn from pg_replication_slots where slot_name = 'sync_slot'] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got deactivated and activated again on standby5"); + + # Resume the slot synchronization. It must drop the slot created from + # the stale information, and re-create it from the re-created remote slot + # on retry. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql( + 'postgres', qq[ +select injection_points_detach('replication-slot-create-begin'); +select injection_points_wakeup('replication-slot-create-begin'); +]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot".*\n.*DETAIL: Logical decoding was disabled after the remote slot's restart LSN/, + $log_offset); + $standby5->poll_query_until('postgres', + qq[select restart_lsn >= '$restart_lsn' from pg_replication_slots where slot_name = 'sync_slot'] + ) + or die + "timed out waiting for the slot to be re-created from the re-created remote slot"; + + # The slot created on retry might not be persisted until the remote slot + # catches up with the catalog_xmin computed locally. Drop the remote slot + # to let the slot synchronization finish, keeping logical decoding enabled + # with another slot as the slot synchronization requires it. + $primary->safe_psql( + 'postgres', qq[ +select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); +select pg_drop_replication_slot('sync_slot'); +]); + $primary->wait_for_replay_catchup($standby5); + $psql_sync_slot->quit; + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot4')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5 after the re-creation test" + ); + # Test that logical slot creation on a standby fails cleanly if logical # decoding is concurrently deactivated by the end-of-recovery transition # upon promotion, which cannot find the slot that is not created yet. -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-25 08:02  Nisha Moond <nisha.moond412@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  2 siblings, 0 replies; 59+ messages in thread

From: Nisha Moond @ 2026-09-25 08:02 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Wed, Sep 23, 2026 at 1:45 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > >
> > > On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov <nik@postgres.ai> wrote:
> > > >
> > > > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> > > > <sawada.mshk@gmail.com> wrote:
> > > > > For slot synchronization, the local slot could be created and
> > > > > persisted based on the remote slot information fetched before the
> > > > > deactivation was replayed, leaving a valid slot whose restart_lsn
> > > > > precedes the deactivation. Decoding such a slot after a failover fails
> > > > > with:
> > > > >
> > > > > ERROR: unexpected logical decoding status change 0
> > > > >
> > > > > These races are confined to the narrow window between checking the
> > > > > logical decoding status and the new slot becoming visible; once the
> > > > > slot is visible, the invalidation performed by the deactivation
> > > > > already covers it. So the fix is simple: re-check the logical decoding
> > > > > status after the new slot becomes visible. Regular slot creation
> > > > > raises an error and slot synchronization skips persisting the slot. If
> > > > > the deactivation happens after the recheck instead, it is guaranteed
> > > > > to invalidate the now-visible slot as usual. The attached 0002
> > > > > implements this.
> > > >
> > > > The disable/re-enable case described in the comment above the final
> > > > IsLogicalDecodingEnabled() check in update_and_persist_local_synced_slot() is
> > > > reachable.
> > > >
> > > > On b73d13c3, the reproducer uses this sequence:
> > > >
> > > > 1. Slot sync fetches failover slot S and pauses at
> > > > replication-slot-create-begin, before creating the local slot.
> > > > 2. The primary drops S. The standby replays the logical-decoding
> > > > deactivation while no local S exists to invalidate.
> > > > 3. The primary recreates S. The standby replays the reactivation.
> > > > 4. The old slot sync resumes with the first incarnation's restart_lsn.
> > > >
> > > > The final IsLogicalDecodingEnabled() check now returns true, so the old slot
> > > > information is persisted. After promoting the standby, decoding that slot
> > > > fails with:
> > > >
> > > > ERROR: unexpected logical decoding status change 0
> > >
> > > Thank you for the report. Yes, while the window is very short in
> > > practice, it indeed happens if the logical decoding is disabled and
> > > re-enabled (by dropping and creating the same name failover slot)
> > > between the slotsync worker fetches the slot information and creates
> > > it.
> > >
> > > It actually hits my concern mentioned in the comment in
> > > update_and_persist_local_synced_slot():
> > >
> > >      * XXX: this check cannot detect the case where logical decoding is
> > >      * already re-enabled by a slot creation on the primary at this point.
> > >      * Detecting that would require comparing the slot's restart_lsn with the
> > >      * LSN at which logical decoding was last enabled.
> > >
> > > > The attached patch adds a logical-decoding status generation. Slot sync
> > > > records it before fetching remote slot information and refuses to persist a
> > > > new slot if the generation changed in the meantime. It drops the temporary
> > > > slot so that the next attempt fetches the current incarnation.
> > >
> > >  Thank you for the patch.
> > >
> > > An alternative approach that I think is better is to have the LSN of
> > > the last replayed status change record in LogicalDecodingCtlData, and
> > > check if logical decoding has been enabled since the remote slot's
> > > restart_lsn. That's simpler than the proposed approach as we don't
> > > need to increment the generation counter at both activation and
> > > deactivation (which is not necessary outside recovery), nor to add
> > > logical_decoding_generation to RemoteSlot. It also checks what we
> > > actually need, that is, whether the WAL from the restart_lsn can be
> > > decoded, rather than whether the status changed while synchronizing
> > > slots.
> > >
> > > Also, I think it's better to move the check to right after
> > > ReplicationSlotCreate() in synchronize_one_slot() because (1) it can
> > > simplify the code flow as we don't need to care about the slot dropped
> > > in update_and_persist_local_synced_slot(), (2) it can save the WAL
> > > reservation and the xmin_horizon computation, and (3) IIUC with the
> > > proposed patch, the check can be bypassed when
> > > update_and_persist_local_synced_slot() returns early due to
> > > slotsync_skip_reason, leaving a temporary slot with the stale
> > > restart_lsn. Once the slot passes the check right after its creation,
> > > a later deactivation invalidates the slot, so we don't need to check
> > > it again before persisting the slot.
> > >
> > > I've attached the patch.
> > >
> >
> > I tested the patch and it fixes the problem. I found no critical
> > issues. A couple of comments:
> > 1) Now that a newly created synced slot is dropped on a failed new
> > check rather than kept as RS_TEMPORARY, a standby that is lagging in
> > replay can end up creating and dropping the slot on every sync cycle.
> > For example, replay is paused with pg_wal_replay_pause() or
> > recovery_min_apply_delay is large. After the primary turns logical
> > decoding off and then on again, the standby receives the activation
> > record but doesn't replay it. Meanwhile the slotsync worker keeps
> > fetching the failover slot, creates it, fails the new
> > IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> > every cycle until the record is replayed.
> >
> > Each cycle creates the slot on disk and a pgstat entry, then removes
> > both again. I think this can be avoided with a cheaper pre-check,
> > IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> > ReplicationSlotCreate().
> >
> > Thoughts?
>
> I agree with your analysis. I think that in this case, the logical
> slot doesn't need to be dropped because WAL records after its
> restart_lsn are written with logical decoding information. Thinking on
> IsLogicalDecodingEnabledSince() further, I think it can work fine for
> the slot only when the replay LSN >= slot's restart_lsn. If the slot's
> restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
> skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
> have to be recreated only in the disable/re-enable case.
>

This solution is better than my suggestion. I tested v2 for both the
original problem and the standby-lagging case, and it works as
expected. In the lagging case, the slot now remains in the temporary
state and is not recreated in a loop.

> >
> > 2) The overview comment at the top of slotsync.c explains each reason
> > a slot isn't synced yet, but it doesn't mention this new
> > drop-and-retry case. Should we add it there too?
>
> The patch describes the details of the disabled/re-enabled case in
> synchronize_one_slot() and it looks sufficient to me.
>

Okay.

> I've updated the patch for the above idea. In this version, the patch
> tracks only the last STATUS_CHANGE record that enables logical
> decoding, which makes it easy to check if logical decoding has
> continuously been enabled since the remote slot's restart_lsn.
>

Overall, the patch LGTM. I have no further comments.

--
Thanks,
Nisha






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-25 09:28  shveta malik <shveta.malik@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  2 siblings, 1 reply; 59+ messages in thread

From: shveta malik @ 2026-09-25 09:28 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers; shveta malik <shveta.malik@gmail.com>

On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> > I tested the patch and it fixes the problem. I found no critical
> > issues. A couple of comments:
> > 1) Now that a newly created synced slot is dropped on a failed new
> > check rather than kept as RS_TEMPORARY, a standby that is lagging in
> > replay can end up creating and dropping the slot on every sync cycle.
> > For example, replay is paused with pg_wal_replay_pause() or
> > recovery_min_apply_delay is large. After the primary turns logical
> > decoding off and then on again, the standby receives the activation
> > record but doesn't replay it. Meanwhile the slotsync worker keeps
> > fetching the failover slot, creates it, fails the new
> > IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> > every cycle until the record is replayed.
> >
> > Each cycle creates the slot on disk and a pgstat entry, then removes
> > both again. I think this can be avoided with a cheaper pre-check,
> > IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> > ReplicationSlotCreate().
> >
> > Thoughts?
>
> I agree with your analysis. I think that in this case, the logical
> slot doesn't need to be dropped because WAL records after its
> restart_lsn are written with logical decoding information. Thinking on
> IsLogicalDecodingEnabledSince() further, I think it can work fine for
> the slot only when the replay LSN >= slot's restart_lsn. If the slot's
> restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
> skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
> have to be recreated only in the disable/re-enable case.

I agree with the problem and solution, but I don't think ths slot will
later be skipped with 'SS_SKIP_WAL_NOT_FLUSHED' as the WALs are
already flushed; it is the replay which is slow and that check
compares against GetStandbyFlushRecPtr(), not replay position I think
it will wait somewhere in
LogicalSlotAdvanceAndCheckSnapState()-->read_local_xlog_page_guts as
'wait_for_wal' is true and standy then waits for replay to happen. If
my understanding is correct, slotsync will be stuck on that one slot
untli replays happen, but let's see what Nisha has found in her tests.
I might be wrong too.

--I found that comments 1 and 2 in my previous email about set/reset
of 'last_replayed_enable_lsn' are missed to be addressed in v2.

--Also v2 does not apply through 'git am'.

--I have a suggestion about comment improvement in
synchronize_one_slot(), attached the patch. Please incorporate these
changes if you agree.

thanks
Shveta

Attachments:

0001-comment-change.patch.txt (text/plain, 4.2K) download From d8b4985f88f579942cb1c13e67f146fb32d76ba9 Mon Sep 17 00:00:00 2001 From: Shveta Malik <shveta.malik@gmail.com> Date: Fri, 25 Sep 2026 14:48:15 +0530 Subject: [PATCH] comment change --- src/backend/replication/logical/slotsync.c | 51 ++++++++++++---------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index a07118c30a7..715ef6439bc 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -868,32 +868,39 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, true); /* - * The remote slot information can predate a status change record that - * this standby has already replayed. That happens when the last - * logical slot on the primary is dropped, and possibly re-created - * with the same name, after fetch_remote_slots() ran: the - * deactivation could not invalidate our slot because it did not exist - * yet, and WAL following the remote restart_lsn may lack the - * information logical decoding needs. Checking only whether logical - * decoding is enabled is not enough, as it can have been disabled and - * enabled again in the meantime. + * The remote slot's restart_lsn can predate a status change record + * this standby has already replayed: the primary drops the last + * logical slot, possibly recreating it with the same name, after + * fetch_remote_slots() ran. The resulting deactivation record could + * not invalidate our slot, since it didn't exist yet, so WAL + * following the (stale) remote restart_lsn may lack the information + * logical decoding needs. Checking only whether logical decoding is + * currently enabled is not enough, since it may have been disabled + * and re-enabled since the remote slot information was fetched. * - * The check has to come after ReplicationSlotCreate(), which makes - * the slot both visible and acquired. A deactivation replayed from - * here on finds the slot in InvalidatePossiblyObsoleteSlot(), signals - * a recovery conflict and waits for the slot to be released before - * invalidating it, so replay cannot get past that record behind our - * back. That is also why the status needs no recheck before the slot - * is persisted. (The invalidation is performed only in hot standby, - * which slot synchronization requires anyway.) + * The check must run after ReplicationSlotCreate(), which makes the + * slot visible and acquired. From this point on, a deactivation + * record finds the slot in InvalidatePossiblyObsoleteSlot(), signals + * a recovery conflict, and waits for the slot to be released before + * invalidating it (only in hot standby, which slot synchronization + * requires anyway). Replay therefore cannot get past that record + * behind our back, so the slot never needs to be rechecked before + * being persisted. * - * WAL beyond the replay position tells us nothing, so a remote - * restart_lsn past it is accepted and left to the interlock above. + * The check only runs once replay has reached the remote restart_lsn; + * otherwise it is skipped and the slot is kept as-is. Without this, a + * standby lagging behind the primary (replay paused, or a large + * recovery_min_apply_delay) could fetch a live, valid restart_lsn + * from the primary and have it rejected by + * StandbyLogicalDecodingEnabledSince(), whose answer reflects only + * WAL replayed so far and says nothing about an LSN replay hasn't + * reached yet. That would drop a perfectly good slot every cycle. * * The comparison uses the remote restart_lsn rather than the local - * one, so a slot that would have been usable may be dropped; the next - * cycle fetches fresh information. The slot cannot be kept, as it - * would go on using the stale restart_lsn. + * one, so a slot that would have been usable may still be dropped; + * the next cycle fetches fresh remote information. The slot can't be + * kept in that case, since it would go on using the stale + * restart_lsn. */ replay_lsn = GetXLogReplayRecPtr(NULL); if (remote_slot->restart_lsn <= replay_lsn && -- 2.34.1
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-25 13:21  Zhijie Hou <houzhijie22@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  2 siblings, 1 reply; 59+ messages in thread

From: Zhijie Hou @ 2026-09-25 13:21 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Hi,

On Fri, Sep 25, 2026 at 6:09 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > I tested the patch and it fixes the problem. I found no critical
> > issues. A couple of comments:
> > 1) Now that a newly created synced slot is dropped on a failed new
> > check rather than kept as RS_TEMPORARY, a standby that is lagging in
> > replay can end up creating and dropping the slot on every sync cycle.
> > For example, replay is paused with pg_wal_replay_pause() or
> > recovery_min_apply_delay is large. After the primary turns logical
> > decoding off and then on again, the standby receives the activation
> > record but doesn't replay it. Meanwhile the slotsync worker keeps
> > fetching the failover slot, creates it, fails the new
> > IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> > every cycle until the record is replayed.
> >
> > Each cycle creates the slot on disk and a pgstat entry, then removes
> > both again. I think this can be avoided with a cheaper pre-check,
> > IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> > ReplicationSlotCreate().
> >
> > Thoughts?
>
> I agree with your analysis. I think that in this case, the logical
> slot doesn't need to be dropped because WAL records after its
> restart_lsn are written with logical decoding information. Thinking on
> IsLogicalDecodingEnabledSince() further, I think it can work fine for
> the slot only when the replay LSN >= slot's restart_lsn. If the slot's
> restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
> skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
> have to be recreated only in the disable/re-enable case.

The patch looks good to me overall, but I have a question for the check of
replay position:

+ replay_lsn = GetXLogReplayRecPtr(NULL);
+ if (remote_slot->restart_lsn <= replay_lsn &&

If the goal is to avoid retrying when the standby is lagging, couldn't we
simply avoid setting slot_persistence_pending = true in this case? The original
slot is dropped anyway, and any slot re-created later is a different one. This
seems more similar to the SS_SKIP_INVALID case, where we don't retry even if a
re-created slot exists. I think that would also make the logic simpler.

Best Regards,
Zhijie Hou






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-25 22:23  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Zhijie Hou <houzhijie22@gmail.com>
  0 siblings, 0 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-09-25 22:23 UTC (permalink / raw)
  To: Zhijie Hou <houzhijie22@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Fri, Sep 25, 2026 at 6:21 AM Zhijie Hou <houzhijie22@gmail.com> wrote:
>
> Hi,
>
> On Fri, Sep 25, 2026 at 6:09 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > I tested the patch and it fixes the problem. I found no critical
> > > issues. A couple of comments:
> > > 1) Now that a newly created synced slot is dropped on a failed new
> > > check rather than kept as RS_TEMPORARY, a standby that is lagging in
> > > replay can end up creating and dropping the slot on every sync cycle.
> > > For example, replay is paused with pg_wal_replay_pause() or
> > > recovery_min_apply_delay is large. After the primary turns logical
> > > decoding off and then on again, the standby receives the activation
> > > record but doesn't replay it. Meanwhile the slotsync worker keeps
> > > fetching the failover slot, creates it, fails the new
> > > IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> > > every cycle until the record is replayed.
> > >
> > > Each cycle creates the slot on disk and a pgstat entry, then removes
> > > both again. I think this can be avoided with a cheaper pre-check,
> > > IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> > > ReplicationSlotCreate().
> > >
> > > Thoughts?
> >
> > I agree with your analysis. I think that in this case, the logical
> > slot doesn't need to be dropped because WAL records after its
> > restart_lsn are written with logical decoding information. Thinking on
> > IsLogicalDecodingEnabledSince() further, I think it can work fine for
> > the slot only when the replay LSN >= slot's restart_lsn. If the slot's
> > restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
> > skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
> > have to be recreated only in the disable/re-enable case.
>
> The patch looks good to me overall, but I have a question for the check of
> replay position:
>
> + replay_lsn = GetXLogReplayRecPtr(NULL);
> + if (remote_slot->restart_lsn <= replay_lsn &&
>
> If the goal is to avoid retrying when the standby is lagging, couldn't we
> simply avoid setting slot_persistence_pending = true in this case? The original
> slot is dropped anyway, and any slot re-created later is a different one. This
> seems more similar to the SS_SKIP_INVALID case, where we don't retry even if a
> re-created slot exists. I think that would also make the logic simpler.

I think the point is that StandbyLogicalDecodingEnabledSince() cannot
answer for an LSN that the standby hasn't replayed yet. If restart_lsn
is ahead of the replay LSN, we would end up answering "no" in this
case and dropping the slot unnecessarily even if the primary already
enables and has a valid logical slot. This would be repeated until the
standby replayed the STATUS_CHANGE record that enables logical
decoding.

I don't think SS_SKIP_INVALID is quite the same situation. There the
remote slot is really invalidated and there is nothing to wait for,
whereas here the remote slot is healthy and becomes syncable as soon
as replay catches up.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com





^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-25 22:24  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 4 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-09-25 22:24 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Fri, Sep 25, 2026 at 2:28 AM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > > I tested the patch and it fixes the problem. I found no critical
> > > issues. A couple of comments:
> > > 1) Now that a newly created synced slot is dropped on a failed new
> > > check rather than kept as RS_TEMPORARY, a standby that is lagging in
> > > replay can end up creating and dropping the slot on every sync cycle.
> > > For example, replay is paused with pg_wal_replay_pause() or
> > > recovery_min_apply_delay is large. After the primary turns logical
> > > decoding off and then on again, the standby receives the activation
> > > record but doesn't replay it. Meanwhile the slotsync worker keeps
> > > fetching the failover slot, creates it, fails the new
> > > IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> > > every cycle until the record is replayed.
> > >
> > > Each cycle creates the slot on disk and a pgstat entry, then removes
> > > both again. I think this can be avoided with a cheaper pre-check,
> > > IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> > > ReplicationSlotCreate().
> > >
> > > Thoughts?
> >
> > I agree with your analysis. I think that in this case, the logical
> > slot doesn't need to be dropped because WAL records after its
> > restart_lsn are written with logical decoding information. Thinking on
> > IsLogicalDecodingEnabledSince() further, I think it can work fine for
> > the slot only when the replay LSN >= slot's restart_lsn. If the slot's
> > restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
> > skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
> > have to be recreated only in the disable/re-enable case.
>
> I agree with the problem and solution, but I don't think ths slot will
> later be skipped with 'SS_SKIP_WAL_NOT_FLUSHED' as the WALs are
> already flushed; it is the replay which is slow and that check
> compares against GetStandbyFlushRecPtr(), not replay position I think
> it will wait somewhere in
> LogicalSlotAdvanceAndCheckSnapState()-->read_local_xlog_page_guts as
> 'wait_for_wal' is true and standy then waits for replay to happen. If
> my understanding is correct, slotsync will be stuck on that one slot
> untli replays happen, but let's see what Nisha has found in her tests.
> I might be wrong too.

You're right, if only the replay is delayed, it can end up waiting in
read_local_xlog_page_guts(). But I think this is pre-existing behavior
for a remote slot whose confirmed_lsn is ahead of the standby's replay
position.

On the other hand, if the WAL has not even been flushed on the standby
yet, we skip the slot with SS_SKIP_WAL_NOT_FLUSHED before reaching
that point. The temporary slot is kept and we retry in the next cycle,
so we don't get stuck there.

>
> --I found that comments 1 and 2 in my previous email about set/reset
> of 'last_replayed_enable_lsn' are missed to be addressed in v2.
>
> --Also v2 does not apply through 'git am'.
>
> --I have a suggestion about comment improvement in
> synchronize_one_slot(), attached the patch. Please incorporate these
> changes if you agree.

Sorry I forgot to mention about comment 1 and 2; since the updated
patch renamed the field name to last_replayed_enable_lsn I think we
don't necessarily need to reset it at
UpdateLogicalDecodingStatusEndOfRecovery(). Also it renamed the
function name to StandbyLogicalDecodingEnabledSince() so it makes
sense to me to leave the field. As for comment 2, I think it's better
to have an shmem-init function for LogicalDecodingCtl rather than
initializing the new field in StartupLogicalDecodingStatus(). So I
prepared a patch for that (0001 patch).

I've incorporated your comment suggestions, and updated cosmetic
things.Please review them.


Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments: download all (2 files, .tar.gz)

v3-0002-Fix-slotsync-when-logical-decoding-is-disabled-an.patch (application/x-patch, 16.3K) download From 5000e2a6dd91fa8ef8a5442ab664462487dbf226 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Tue, 22 Sep 2026 10:40:46 -0700 Subject: [PATCH v3 2/2] Fix slotsync when logical decoding is disabled and re-enabled. Commit 6aba42c660c made slot synchronization skip persisting a new slot if logical decoding got disabled after the remote slot information was fetched. As noted in its XXX comment, the check missed the case where the last logical slot on the primary is dropped and re-created with the same name in the meantime. If the standby had replayed both the deactivation and the re-activation by then, the slot was persisted with a restart_lsn preceding the deactivation. Subsequent synchronization cycles failed with "unexpected logical decoding status change" when advancing the slot, which also stopped the synchronization of all other failover slots, and the slot could not be decoded after promotion. Fix this by remembering the end LSN of the last replayed XLOG_LOGICAL_DECODING_STATUS_CHANGE record that enables logical decoding, and by requiring the remote restart_lsn to be at or after it right after creating the local slot. Once the slot exists, a later deactivation invalidates it, so remove the check before persisting the slot. We compare the remote restart_lsn rather than the local one, so we may drop a slot that would have been usable, but the retry in the next synchronization cycle fetches fresh information. Reported-by: Nik Samokhvalov <nik@postgres.ai> Reviewed-by: shveta malik <shveta.malik@gmail.com> Reviewed-by: Nisha Moond <nisha.moond412@gmail.com> Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/access/transam/xlog.c | 2 +- src/backend/replication/logical/logicalctl.c | 66 +++++++++++++- src/backend/replication/logical/slotsync.c | 88 +++++++++++-------- src/include/replication/logicalctl.h | 5 +- .../recovery/t/051_effective_wal_level.pl | 79 +++++++++++++++++ 5 files changed, 201 insertions(+), 39 deletions(-) diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index 9ec0be77ca0..91b241b1210 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -9649,7 +9649,7 @@ xlog_redo(XLogReaderState *record) * subsequent WAL records, which may not contain logical information. */ if (status) - EnableLogicalDecoding(); + EnableLogicalDecoding(lsn); else DisableLogicalDecoding(); diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index fd4ab5f7508..f0df0fabee4 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -64,6 +64,7 @@ #include "postgres.h" #include "access/xloginsert.h" +#include "access/xlogrecovery.h" #include "catalog/pg_control.h" #include "miscadmin.h" #include "replication/slot.h" @@ -95,6 +96,22 @@ typedef struct LogicalDecodingCtlData /* True if logical decoding might need to be disabled */ bool pending_disable; + + /* + * End LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record that + * enabled logical decoding, or InvalidXLogRecPtr if none has been + * replayed since the server started. Checking it with + * logical_decoding_enabled tells from which point on WAL was written with + * logical decoding enabled; see StandbyLogicalDecodingEnabledSince(). + * + * WAL records that disable logical decoding are deliberately not tracked + * here. logical_decoding_enabled is false while decoding is off, which is + * all the check needs. + * + * This is maintained only during recovery and is not persisted, so it + * says nothing about a status change replayed in an earlier server run. + */ + XLogRecPtr last_replayed_enable_lsn; } LogicalDecodingCtlData; static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; @@ -144,6 +161,7 @@ LogicalDecodingCtlShmemInit(void *arg) LogicalDecodingCtl->xlog_logical_info = false; LogicalDecodingCtl->logical_decoding_enabled = false; LogicalDecodingCtl->pending_disable = false; + LogicalDecodingCtl->last_replayed_enable_lsn = InvalidXLogRecPtr; } /* @@ -220,6 +238,35 @@ IsLogicalDecodingEnabled(void) return enabled; } +/* + * Return true if logical decoding has been enabled continuously from the given + * LSN up to the current replay position, that is, if the WAL in that range + * was written with logical decoding enabled. + * + * The given LSN must have been replayed already; nothing can be said about + * WAL this server has not replayed yet. The caller is responsible for checking + * that. + * + * A true result therefore covers only the WAL replayed so far. A deactivation + * replayed after the call still applies, and callers must arrange for that + * themselves. + */ +bool +StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn) +{ + bool result; + + Assert(RecoveryInProgress()); + Assert(lsn <= GetXLogReplayRecPtr(NULL)); + + LWLockAcquire(LogicalDecodingControlLock, LW_SHARED); + result = LogicalDecodingCtl->logical_decoding_enabled && + lsn >= LogicalDecodingCtl->last_replayed_enable_lsn; + LWLockRelease(LogicalDecodingControlLock); + + return result; +} + /* * Returns true if logical WAL logging is enabled based on the shared memory * status. @@ -340,21 +387,36 @@ EnsureLogicalDecodingEnabled(void) */ PG_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); { - EnableLogicalDecoding(); + EnableLogicalDecoding(InvalidXLogRecPtr); } PG_END_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); } /* * A workhorse function to enable logical decoding. + * + * lsn is the end LSN of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record + * being replayed, and is InvalidXLogRecPtr when not called from redo. */ void -EnableLogicalDecoding(void) +EnableLogicalDecoding(XLogRecPtr lsn) { bool in_recovery; LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Remember where logical decoding was enabled. This has to happen before + * the early return below, because replay can reach here with the status + * already on. For example, CreateCheckPoint() fixes the redo point before + * it records logicalDecodingEnabled, so a checkpoint can claim logical + * decoding is enabled while the record that enabled it still follows the + * redo point. + */ + Assert(RecoveryInProgress() == XLogRecPtrIsValid(lsn)); + if (XLogRecPtrIsValid(lsn)) + LogicalDecodingCtl->last_replayed_enable_lsn = lsn; + /* Return if it is already enabled */ if (LogicalDecodingCtl->logical_decoding_enabled) { diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index c0403893e23..0398c935a67 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -718,41 +718,6 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } - /* - * Do not persist the slot if logical decoding got disabled concurrently. - * This can happen if the last logical slot on the primary was dropped and - * the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was - * replayed after we fetched the remote slot information: WAL records - * following the slot's restart_lsn might lack the information required by - * logical decoding, and the slot invalidation performed when replaying - * the record could not find our slot as it was not created yet. - * - * It is important to perform this check after creating the slot and - * before persisting it. This way, even if the status change record is - * replayed after this check, the replay will invalidate our slot. - * - * If the check fails, we keep the temporary slot and let the caller - * retry; the next cycle fetches the remote slot information again and - * will drop this slot as the remote slot no longer exists. - * - * XXX: this check cannot detect the case where logical decoding is - * already re-enabled by a slot creation on the primary at this point. - * Detecting that would require comparing the slot's restart_lsn with the - * LSN at which logical decoding was last enabled. - */ - if (!IsLogicalDecodingEnabled()) - { - ereport(LOG, - errmsg("could not synchronize replication slot \"%s\"", - remote_slot->name), - errdetail("Logical decoding was concurrently disabled.")); - - if (slot_persistence_pending) - *slot_persistence_pending = true; - - return false; - } - ReplicationSlotPersist(); ereport(LOG, @@ -883,6 +848,7 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, { NameData plugin_name; TransactionId xmin_horizon = InvalidTransactionId; + XLogRecPtr replay_lsn; /* Skip creating the local slot if remote_slot is invalidated already */ if (remote_slot->invalidated != RS_INVAL_NONE) @@ -901,6 +867,58 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, remote_slot->failover, true); + /* + * The remote slot information can predate a status change record that + * this standby has already replayed. That happens when the last + * logical slot on the primary is dropped, and possibly re-created + * with the same name, after fetch_remote_slots() ran. The resulting + * deactivation could not invalidate our slot because it did not exist + * yet, and WAL following the (stale) remote restart_lsn may lack the + * information logical decoding needs. Checking only whether logical + * decoding is enabled is not enough, as it can have been disabled and + * enabled again in the meantime. + * + * The check has to come after ReplicationSlotCreate(), which makes + * the slot both visible and acquired. A deactivation replayed from + * here on finds the slot in InvalidatePossiblyObsoleteSlot(), signals + * a recovery conflict and waits for the slot to be released before + * invalidating it (only in hot standby, which slot synchronization + * requires anyway). Replay therefore cannot get past that record + * behind our back, so the slot never needs to be rechecked before + * being persisted. + * + * The check only runs once replay has reached the remote restart_lsn; + * otherwise it is skipped and the slot is kept as-is. Without this, a + * standby lagging behind the primary (replay paused, or a large + * recovery_min_apply_delay) could fetch a live, valid restart_lsn + * from the primary and have it rejected by + * StandbyLogicalDecodingEnabledSince(), whose answer reflects only + * WAL replayed so far and says nothing about an LSN replay hasn't + * reached yet. That would drop a perfectly good slot every cycle. + * + * Even so, the comparison uses the remote restart_lsn rather than the + * local one, so a slot that would have been usable may be dropped; + * the next cycle fetches fresh information. The slot cannot be kept, + * as it would go on using the stale restart_lsn. + */ + replay_lsn = GetXLogReplayRecPtr(NULL); + if (remote_slot->restart_lsn <= replay_lsn && + !StandbyLogicalDecodingEnabledSince(remote_slot->restart_lsn)) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding was disabled after the remote slot's restart LSN %X/%08X.", + LSN_FORMAT_ARGS(remote_slot->restart_lsn))); + + ReplicationSlotDropAcquired(false); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + /* For shorter lines. */ slot = MyReplicationSlot; diff --git a/src/include/replication/logicalctl.h b/src/include/replication/logicalctl.h index 0bc1302f130..97cacb02e4e 100644 --- a/src/include/replication/logicalctl.h +++ b/src/include/replication/logicalctl.h @@ -14,14 +14,17 @@ #ifndef LOGICALCTL_H #define LOGICALCTL_H +#include "access/xlogdefs.h" + extern void StartupLogicalDecodingStatus(bool last_status); extern void InitializeProcessXLogLogicalInfo(void); extern bool ProcessBarrierUpdateXLogLogicalInfo(void); extern bool IsLogicalDecodingEnabled(void); +extern bool StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn); extern bool IsXLogLogicalInfoEnabled(void); extern void AtEOXact_LogicalCtl(void); extern void EnsureLogicalDecodingEnabled(void); -extern void EnableLogicalDecoding(void); +extern void EnableLogicalDecoding(XLogRecPtr lsn); extern void RequestDisableLogicalDecoding(void); extern void DisableLogicalDecodingIfNecessary(void); extern void DisableLogicalDecoding(void); diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index b11690863d9..f153ae81828 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -598,6 +598,85 @@ select pg_sync_replication_slots(); '0', "no synced slot is left behind on standby5"); + # Test the same race, but where the slot is re-created on the primary + # before the slot synchronization resumes. Logical decoding is enabled + # again at the time the local slot is created, so checking the logical + # decoding status alone cannot tell that the remote slot information + # predates the deactivation. + + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5 for the re-creation test" + ); + + $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + + # Drop and re-create the slot, and wait for the standby to replay both + # the deactivation and the activation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + my $restart_lsn = $primary->safe_psql('postgres', + qq[select restart_lsn from pg_replication_slots where slot_name = 'sync_slot'] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got deactivated and activated again on standby5"); + + # Resume the slot synchronization. It must drop the slot created from + # the stale information, and re-create it from the re-created remote slot + # on retry. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql( + 'postgres', qq[ +select injection_points_detach('replication-slot-create-begin'); +select injection_points_wakeup('replication-slot-create-begin'); +]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot".*\n.*DETAIL: Logical decoding was disabled after the remote slot's restart LSN/, + $log_offset); + $standby5->poll_query_until('postgres', + qq[select restart_lsn >= '$restart_lsn' from pg_replication_slots where slot_name = 'sync_slot'] + ) + or die + "timed out waiting for the slot to be re-created from the re-created remote slot"; + + # The slot created on retry might not be persisted until the remote slot + # catches up with the catalog_xmin computed locally. Drop the remote slot + # to let the slot synchronization finish, keeping logical decoding enabled + # with another slot as the slot synchronization requires it. + $primary->safe_psql( + 'postgres', qq[ +select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); +select pg_drop_replication_slot('sync_slot'); +]); + $primary->wait_for_replay_catchup($standby5); + $psql_sync_slot->quit; + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot4')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5 after the re-creation test" + ); + # Test that logical slot creation on a standby fails cleanly if logical # decoding is concurrently deactivated by the end-of-recovery transition # upon promotion. -- 2.55.0
v3-0001-Add-an-init-callback-for-the-logical-decoding-con.patch (application/x-patch, 1.9K) download From db4c91e7a48f3eb025e7fc5c665b46faea3f83ad Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Fri, 25 Sep 2026 10:45:37 -0700 Subject: [PATCH v3 1/2] Add an init callback for the logical decoding control data. LogicalDecodingCtl had no init callback so there is no guarantee that its fields are initialized. Its startup function StartupLogicalDecodingStatus() also returns wihtout touching the fields when wal_level is 'minimal'. Intialize them in an init callback explcitly. This is not a bug fix but we just shouldn't be depending on the allocator by accident. Backpatch to v19, where logicalctl.c was introduced. Reviewed-by: Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 642d965bd1c..fd4ab5f7508 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -100,9 +100,11 @@ typedef struct LogicalDecodingCtlData static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; static void LogicalDecodingCtlShmemRequest(void *arg); +static void LogicalDecodingCtlShmemInit(void *arg); const ShmemCallbacks LogicalDecodingCtlShmemCallbacks = { .request_fn = LogicalDecodingCtlShmemRequest, + .init_fn = LogicalDecodingCtlShmemInit, }; /* @@ -136,6 +138,14 @@ LogicalDecodingCtlShmemRequest(void *arg) ); } +static void +LogicalDecodingCtlShmemInit(void *arg) +{ + LogicalDecodingCtl->xlog_logical_info = false; + LogicalDecodingCtl->logical_decoding_enabled = false; + LogicalDecodingCtl->pending_disable = false; +} + /* * Initialize the logical decoding status in shmem at server startup. This * must be called ONCE during postmaster or standalone-backend startup. -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-26 21:44  Amit Kapila <amit.kapila16@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 1 reply; 59+ messages in thread

From: Amit Kapila @ 2026-09-26 21:44 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Fri, Sep 25, 2026 at 6:25 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> I've incorporated your comment suggestions, and updated cosmetic
> things.Please review them.
>

+ /*
+ * The remote slot information can predate a status change record that
+ * this standby has already replayed. That happens when the last
+ * logical slot on the primary is dropped, and possibly re-created
+ * with the same name, after fetch_remote_slots() ran. The resulting
+ * deactivation could not invalidate our slot because it did not exist
+ * yet, and WAL following the (stale) remote restart_lsn may lack the
+ * information logical decoding needs. Checking only whether logical
+ * decoding is enabled is not enough, as it can have been disabled and
+ * enabled again in the meantime.
+ *
+ * The check has to come after ReplicationSlotCreate(), which makes
+ * the slot both visible and acquired. A deactivation replayed from
+ * here on finds the slot in InvalidatePossiblyObsoleteSlot(), signals
+ * a recovery conflict and waits for the slot to be released before
+ * invalidating it (only in hot standby, which slot synchronization
+ * requires anyway). Replay therefore cannot get past that record
+ * behind our back, so the slot never needs to be rechecked before
+ * being persisted.
+ *
+ * The check only runs once replay has reached the remote restart_lsn;
+ * otherwise it is skipped and the slot is kept as-is. Without this, a
+ * standby lagging behind the primary (replay paused, or a large
+ * recovery_min_apply_delay) could fetch a live, valid restart_lsn
+ * from the primary and have it rejected by
+ * StandbyLogicalDecodingEnabledSince(), whose answer reflects only
+ * WAL replayed so far and says nothing about an LSN replay hasn't
+ * reached yet. That would drop a perfectly good slot every cycle.
+ *
+ * Even so, the comparison uses the remote restart_lsn rather than the
+ * local one, so a slot that would have been usable may be dropped;
+ * the next cycle fetches fresh information. The slot cannot be kept,
+ * as it would go on using the stale restart_lsn.
+ */
+ replay_lsn = GetXLogReplayRecPtr(NULL);
+ if (remote_slot->restart_lsn <= replay_lsn &&
+ !StandbyLogicalDecodingEnabledSince(remote_slot->restart_lsn))
+ {
+ ereport(LOG,
+ errmsg("could not synchronize replication slot \"%s\"",
+   remote_slot->name),
+ errdetail("Logical decoding was disabled after the remote slot's
restart LSN %X/%08X.",
+  LSN_FORMAT_ARGS(remote_slot->restart_lsn)));
+
+ ReplicationSlotDropAcquired(false);
+
+ if (slot_persistence_pending)
+ *slot_persistence_pending = true;
+
+ return false;
+ }
+
  /* For shorter lines. */
  slot = MyReplicationSlot;

It is not clear from comments why it is okay to proceed when
remote_slot->restart_lsn > replay_lsn? Because if it is possible to
persist the slot in that case then the above issue can hit later say
if the promotion happens. I think it is not possible to persist the
slot and if that is the case, then we can capture it in comments on
the lines:  (The check is skipped until replay reaches the remote
restart_lsn, as StandbyLogicalDecodingEnabledSince() describes
replayed WAL only and would otherwise reject a valid restart_lsn from
a lagging standby. Skipping it lets no bad slot through, as the slot
is not persisted in this cycle anyway. It starts out with the remote
restart_lsn, see reserve_wal_for_local_slot(), and
update_local_synced_slot() can neither find a serialized snapshot at
an LSN this standby has not replayed nor build one by decoding WAL it
has not replayed. It therefore reports no consistent snapshot, the
slot stays temporary, and a later cycle retries it once replay has
advanced.).

If the above reasoning is correct it doesn't seem like a good idea to
split the safety of the above mechanism in different functions.
Instead, we can move the new check just before
update_and_persist_local_synced_slot() and then avoid relying on the
code in update_and_persist_local_synced_slot() that can persist the
slot.

-- 
With Regards,
Amit Kapila.






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-28 05:00  shveta malik <shveta.malik@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 0 replies; 59+ messages in thread

From: shveta malik @ 2026-09-28 05:00 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers; shveta malik <shveta.malik@gmail.com>

On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Fri, Sep 25, 2026 at 2:28 AM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > >
> > > > I tested the patch and it fixes the problem. I found no critical
> > > > issues. A couple of comments:
> > > > 1) Now that a newly created synced slot is dropped on a failed new
> > > > check rather than kept as RS_TEMPORARY, a standby that is lagging in
> > > > replay can end up creating and dropping the slot on every sync cycle.
> > > > For example, replay is paused with pg_wal_replay_pause() or
> > > > recovery_min_apply_delay is large. After the primary turns logical
> > > > decoding off and then on again, the standby receives the activation
> > > > record but doesn't replay it. Meanwhile the slotsync worker keeps
> > > > fetching the failover slot, creates it, fails the new
> > > > IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> > > > every cycle until the record is replayed.
> > > >
> > > > Each cycle creates the slot on disk and a pgstat entry, then removes
> > > > both again. I think this can be avoided with a cheaper pre-check,
> > > > IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> > > > ReplicationSlotCreate().
> > > >
> > > > Thoughts?
> > >
> > > I agree with your analysis. I think that in this case, the logical
> > > slot doesn't need to be dropped because WAL records after its
> > > restart_lsn are written with logical decoding information. Thinking on
> > > IsLogicalDecodingEnabledSince() further, I think it can work fine for
> > > the slot only when the replay LSN >= slot's restart_lsn. If the slot's
> > > restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
> > > skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
> > > have to be recreated only in the disable/re-enable case.
> >
> > I agree with the problem and solution, but I don't think ths slot will
> > later be skipped with 'SS_SKIP_WAL_NOT_FLUSHED' as the WALs are
> > already flushed; it is the replay which is slow and that check
> > compares against GetStandbyFlushRecPtr(), not replay position I think
> > it will wait somewhere in
> > LogicalSlotAdvanceAndCheckSnapState()-->read_local_xlog_page_guts as
> > 'wait_for_wal' is true and standy then waits for replay to happen. If
> > my understanding is correct, slotsync will be stuck on that one slot
> > untli replays happen, but let's see what Nisha has found in her tests.
> > I might be wrong too.
>
> You're right, if only the replay is delayed, it can end up waiting in
> read_local_xlog_page_guts(). But I think this is pre-existing behavior
> for a remote slot whose confirmed_lsn is ahead of the standby's replay
> position.

Yes. I agree.

>
> On the other hand, if the WAL has not even been flushed on the standby
> yet, we skip the slot with SS_SKIP_WAL_NOT_FLUSHED before reaching
> that point. The temporary slot is kept and we retry in the next cycle,
> so we don't get stuck there.

Right.

> >
> > --I found that comments 1 and 2 in my previous email about set/reset
> > of 'last_replayed_enable_lsn' are missed to be addressed in v2.
> >
> > --Also v2 does not apply through 'git am'.
> >
> > --I have a suggestion about comment improvement in
> > synchronize_one_slot(), attached the patch. Please incorporate these
> > changes if you agree.
>
> Sorry I forgot to mention about comment 1 and 2; since the updated
> patch renamed the field name to last_replayed_enable_lsn I think we
> don't necessarily need to reset it at
> UpdateLogicalDecodingStatusEndOfRecovery().

Okay. Works for me.

> Also it renamed the
> function name to StandbyLogicalDecodingEnabledSince() so it makes
> sense to me to leave the field. As for comment 2, I think it's better
> to have an shmem-init function for LogicalDecodingCtl rather than
> initializing the new field in StartupLogicalDecodingStatus(). So I
> prepared a patch for that (0001 patch).

Okay, makes sense.

> I've incorporated your comment suggestions, and updated cosmetic
> things.Please review them.
>

Okay, looks good. I can have a look again once Amit's suggestion is
incorporated.

thanks
Shveta






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-28 05:03  Nisha Moond <nisha.moond412@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 0 replies; 59+ messages in thread

From: Nisha Moond @ 2026-09-28 05:03 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Fri, Sep 25, 2026 at 2:28 AM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > >
> > > > I tested the patch and it fixes the problem. I found no critical
> > > > issues. A couple of comments:
> > > > 1) Now that a newly created synced slot is dropped on a failed new
> > > > check rather than kept as RS_TEMPORARY, a standby that is lagging in
> > > > replay can end up creating and dropping the slot on every sync cycle.
> > > > For example, replay is paused with pg_wal_replay_pause() or
> > > > recovery_min_apply_delay is large. After the primary turns logical
> > > > decoding off and then on again, the standby receives the activation
> > > > record but doesn't replay it. Meanwhile the slotsync worker keeps
> > > > fetching the failover slot, creates it, fails the new
> > > > IsLogicalDecodingEnabledSince() check, and drops it. This repeats
> > > > every cycle until the record is replayed.
> > > >
> > > > Each cycle creates the slot on disk and a pgstat entry, then removes
> > > > both again. I think this can be avoided with a cheaper pre-check,
> > > > IsLogicalDecodingEnabledSince(remote_slot->restart_lsn), before
> > > > ReplicationSlotCreate().
> > > >
> > > > Thoughts?
> > >
> > > I agree with your analysis. I think that in this case, the logical
> > > slot doesn't need to be dropped because WAL records after its
> > > restart_lsn are written with logical decoding information. Thinking on
> > > IsLogicalDecodingEnabledSince() further, I think it can work fine for
> > > the slot only when the replay LSN >= slot's restart_lsn. If the slot's
> > > restart_lsn > replay_lsn, we can leave the slot. Such a slot will be
> > > skipped for SS_SKIP_WAL_NOT_FLUSHED anyway. That way, the slot would
> > > have to be recreated only in the disable/re-enable case.
> >
> > I agree with the problem and solution, but I don't think ths slot will
> > later be skipped with 'SS_SKIP_WAL_NOT_FLUSHED' as the WALs are
> > already flushed; it is the replay which is slow and that check
> > compares against GetStandbyFlushRecPtr(), not replay position I think
> > it will wait somewhere in
> > LogicalSlotAdvanceAndCheckSnapState()-->read_local_xlog_page_guts as
> > 'wait_for_wal' is true and standy then waits for replay to happen. If
> > my understanding is correct, slotsync will be stuck on that one slot
> > untli replays happen, but let's see what Nisha has found in her tests.
> > I might be wrong too.
>
> You're right, if only the replay is delayed, it can end up waiting in
> read_local_xlog_page_guts(). But I think this is pre-existing behavior
> for a remote slot whose confirmed_lsn is ahead of the standby's replay
> position.
>

I confirmed the wait with a test. With replay paused on the standby, a
new failover slot 's' whose position is ahead of replay is created on
the standby as temporary. The slotsync worker then waits in
read_local_xlog_page_guts() for replay to catch up. Meanwhile, a
second slot 't', advanced on the primary only up to an LSN the standby
had already replayed, is not synced until replay is resumed.

Call stack of the slotsync worker:

pg_usleep
read_local_xlog_page_guts
read_local_xlog_page
XLogReadRecord
LogicalSlotAdvanceAndCheckSnapState
update_local_synced_slot
update_and_persist_local_synced_slot
synchronize_one_slot
synchronize_slots
ReplSlotSyncWorkerMain
...

I see the same wait on HEAD without the patch too, so I agree that
this is pre-existing.

--
Thanks,
Nisha






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-28 19:48  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-09-28 19:48 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Sat, Sep 26, 2026 at 2:44 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Fri, Sep 25, 2026 at 6:25 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > I've incorporated your comment suggestions, and updated cosmetic
> > things.Please review them.
> >
>
> + /*
> + * The remote slot information can predate a status change record that
> + * this standby has already replayed. That happens when the last
> + * logical slot on the primary is dropped, and possibly re-created
> + * with the same name, after fetch_remote_slots() ran. The resulting
> + * deactivation could not invalidate our slot because it did not exist
> + * yet, and WAL following the (stale) remote restart_lsn may lack the
> + * information logical decoding needs. Checking only whether logical
> + * decoding is enabled is not enough, as it can have been disabled and
> + * enabled again in the meantime.
> + *
> + * The check has to come after ReplicationSlotCreate(), which makes
> + * the slot both visible and acquired. A deactivation replayed from
> + * here on finds the slot in InvalidatePossiblyObsoleteSlot(), signals
> + * a recovery conflict and waits for the slot to be released before
> + * invalidating it (only in hot standby, which slot synchronization
> + * requires anyway). Replay therefore cannot get past that record
> + * behind our back, so the slot never needs to be rechecked before
> + * being persisted.
> + *
> + * The check only runs once replay has reached the remote restart_lsn;
> + * otherwise it is skipped and the slot is kept as-is. Without this, a
> + * standby lagging behind the primary (replay paused, or a large
> + * recovery_min_apply_delay) could fetch a live, valid restart_lsn
> + * from the primary and have it rejected by
> + * StandbyLogicalDecodingEnabledSince(), whose answer reflects only
> + * WAL replayed so far and says nothing about an LSN replay hasn't
> + * reached yet. That would drop a perfectly good slot every cycle.
> + *
> + * Even so, the comparison uses the remote restart_lsn rather than the
> + * local one, so a slot that would have been usable may be dropped;
> + * the next cycle fetches fresh information. The slot cannot be kept,
> + * as it would go on using the stale restart_lsn.
> + */
> + replay_lsn = GetXLogReplayRecPtr(NULL);
> + if (remote_slot->restart_lsn <= replay_lsn &&
> + !StandbyLogicalDecodingEnabledSince(remote_slot->restart_lsn))
> + {
> + ereport(LOG,
> + errmsg("could not synchronize replication slot \"%s\"",
> +   remote_slot->name),
> + errdetail("Logical decoding was disabled after the remote slot's
> restart LSN %X/%08X.",
> +  LSN_FORMAT_ARGS(remote_slot->restart_lsn)));
> +
> + ReplicationSlotDropAcquired(false);
> +
> + if (slot_persistence_pending)
> + *slot_persistence_pending = true;
> +
> + return false;
> + }
> +
>   /* For shorter lines. */
>   slot = MyReplicationSlot;
>
> It is not clear from comments why it is okay to proceed when
> remote_slot->restart_lsn > replay_lsn? Because if it is possible to
> persist the slot in that case then the above issue can hit later say
> if the promotion happens. I think it is not possible to persist the
> slot and if that is the case, then we can capture it in comments on
> the lines:  (The check is skipped until replay reaches the remote
> restart_lsn, as StandbyLogicalDecodingEnabledSince() describes
> replayed WAL only and would otherwise reject a valid restart_lsn from
> a lagging standby. Skipping it lets no bad slot through, as the slot
> is not persisted in this cycle anyway. It starts out with the remote
> restart_lsn, see reserve_wal_for_local_slot(), and
> update_local_synced_slot() can neither find a serialized snapshot at
> an LSN this standby has not replayed nor build one by decoding WAL it
> has not replayed. It therefore reports no consistent snapshot, the
> slot stays temporary, and a later cycle retries it once replay has
> advanced.).

Such a slot won't be persisted before replay catches up, but I think
the reason is slightly different from what you described, and it
doesn't wait for a later cycle. When remote_slot->restart_lsn >
replay_lsn, the check is skipped and we reach
read_local_xlog_page_guts() via LogicalSlotAdvanceAndCheckSnapState(),
where we wait for the replay LSN to catch up to the slot's
confirmed_lsn. It doesn't report "no consistent snapshot". We wait
there, and the slot can then reach a consistent snapshot and be
persisted in the same cycle. The patch doesn't change any of this. The
check on replay_lsn is there so that the new check stays a no-op when
it
has nothing to say about the given LSN.

The reason it's okay to proceed is that we created and acquired the
slot before the wait. If a STATUS_CHANGE record that disables logical
decoding is replayed while we are waiting, the slot invalidation finds
our slot, signals a recovery conflict and waits for us to release it
before invalidating it, and slotsync worker is terminated. So no bad
slot is left behind.

> If the above reasoning is correct it doesn't seem like a good idea to
> split the safety of the above mechanism in different functions.
> Instead, we can move the new check just before
> update_and_persist_local_synced_slot() and then avoid relying on the
> code in update_and_persist_local_synced_slot() that can persist the
> slot.

Does it mean that we return early before calling
update_and_persist_local_synced_slot() if replay_lsn < restart_lsn? If
so, I think it would change the existing behavior rather than fix this
issue.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-09-29 00:35  Amit Kapila <amit.kapila16@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 0 replies; 59+ messages in thread

From: Amit Kapila @ 2026-09-29 00:35 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Mon, Sep 28, 2026 at 3:49 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Sat, Sep 26, 2026 at 2:44 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> >
> > It is not clear from comments why it is okay to proceed when
> > remote_slot->restart_lsn > replay_lsn? Because if it is possible to
> > persist the slot in that case then the above issue can hit later say
> > if the promotion happens. I think it is not possible to persist the
> > slot and if that is the case, then we can capture it in comments on
> > the lines:  (The check is skipped until replay reaches the remote
...
...
>
> Such a slot won't be persisted before replay catches up, but I think
> the reason is slightly different from what you described, and it
> doesn't wait for a later cycle. When remote_slot->restart_lsn >
> replay_lsn, the check is skipped and we reach
> read_local_xlog_page_guts() via LogicalSlotAdvanceAndCheckSnapState(),
> where we wait for the replay LSN to catch up to the slot's
> confirmed_lsn. It doesn't report "no consistent snapshot". We wait
> there, and the slot can then reach a consistent snapshot and be
> persisted in the same cycle. The patch doesn't change any of this. The
> check on replay_lsn is there so that the new check stays a no-op when
> it
> has nothing to say about the given LSN.
>
> The reason it's okay to proceed is that we created and acquired the
> slot before the wait. If a STATUS_CHANGE record that disables logical
> decoding is replayed while we are waiting, the slot invalidation finds
> our slot, signals a recovery conflict and waits for us to release it
> before invalidating it, and slotsync worker is terminated. So no bad
> slot is left behind.
>
> > If the above reasoning is correct it doesn't seem like a good idea to
> > split the safety of the above mechanism in different functions.
> > Instead, we can move the new check just before
> > update_and_persist_local_synced_slot() and then avoid relying on the
> > code in update_and_persist_local_synced_slot() that can persist the
> > slot.
>
> Does it mean that we return early before calling
> update_and_persist_local_synced_slot() if replay_lsn < restart_lsn? If
> so, I think it would change the existing behavior rather than fix this
> issue.
>

Yeah, so we shouldn't do that but let's update the comment why it is
okay to proceed in that case.

-- 
With Regards,
Amit Kapila.






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-01 11:08  Nisha Moond <nisha.moond412@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  3 siblings, 1 reply; 59+ messages in thread

From: Nisha Moond @ 2026-10-01 11:08 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
>
> I've incorporated your comment suggestions, and updated cosmetic
> things.Please review them.
>

Hi,
I reviewed the TAP test and it LGTM. I found no correctness issues,
just a couple of nits compared to the neighboring tests. Please
consider these if they look okay to you:

1) Add the sync_slot condition to injection_points_attach() similar to
the neighboring tests, so the wait happens only when sync_slot itself
is being created.
2) Add a note() after wait_for_event(), as in the other tests, so the
test output shows when the sync is paused at the injection point.

Suggestion:

inline patch 1: src/test/recovery/t/051_effective_wal_level.pl (+1/-1 lines) download inline-1.patch--- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -617,11 +617,12 @@ select pg_sync_replication_slots(); qr/sync_slots/, q(\echo sync_slots select injection_points_set_local(); -select injection_points_attach('replication-slot-create-begin', 'wait'); +select injection_points_attach('replication-slot-create-begin',
'wait', 'sync_slot'); select pg_sync_replication_slots(); )); $standby5->wait_for_event('client backend', 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); # Drop and re-create the slot, and wait for the standby to replay both # the deactivation and the activation. -- Thanks, Nisha ^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-05 22:26  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Nisha Moond <nisha.moond412@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-10-05 22:26 UTC (permalink / raw)
  To: Nisha Moond <nisha.moond412@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
>
> On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> >
> > I've incorporated your comment suggestions, and updated cosmetic
> > things.Please review them.
> >
>
> Hi,
> I reviewed the TAP test and it LGTM. I found no correctness issues,
> just a couple of nits compared to the neighboring tests. Please
> consider these if they look okay to you:
>
> 1) Add the sync_slot condition to injection_points_attach() similar to
> the neighboring tests, so the wait happens only when sync_slot itself
> is being created.
> 2) Add a note() after wait_for_event(), as in the other tests, so the
> test output shows when the sync is paused at the injection point.
>

Both suggestions look good to me. I've incorporated these suggestions
and updated the comment as discussed with Amit. I've attached the
updated patch.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments: download all (2 files, .tar.gz)

v4-0001-Add-an-init-callback-for-the-logical-decoding-con.patch (text/x-patch, 1.9K) download From a9f328eee0cec4d0db677b69f3c94eeec8525230 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Fri, 25 Sep 2026 10:45:37 -0700 Subject: [PATCH v4 1/2] Add an init callback for the logical decoding control data. LogicalDecodingCtl had no init callback so there is no guarantee that its fields are initialized. Its startup function StartupLogicalDecodingStatus() also returns wihtout touching the fields when wal_level is 'minimal'. Intialize them in an init callback explcitly. This is not a bug fix but we just shouldn't be depending on the allocator by accident. Backpatch to v19, where logicalctl.c was introduced. Reviewed-by: Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 642d965bd1c..fd4ab5f7508 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -100,9 +100,11 @@ typedef struct LogicalDecodingCtlData static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; static void LogicalDecodingCtlShmemRequest(void *arg); +static void LogicalDecodingCtlShmemInit(void *arg); const ShmemCallbacks LogicalDecodingCtlShmemCallbacks = { .request_fn = LogicalDecodingCtlShmemRequest, + .init_fn = LogicalDecodingCtlShmemInit, }; /* @@ -136,6 +138,14 @@ LogicalDecodingCtlShmemRequest(void *arg) ); } +static void +LogicalDecodingCtlShmemInit(void *arg) +{ + LogicalDecodingCtl->xlog_logical_info = false; + LogicalDecodingCtl->logical_decoding_enabled = false; + LogicalDecodingCtl->pending_disable = false; +} + /* * Initialize the logical decoding status in shmem at server startup. This * must be called ONCE during postmaster or standalone-backend startup. -- 2.55.0
v4-0002-Fix-slotsync-when-logical-decoding-is-disabled-an.patch (text/x-patch, 16.3K) download From d513ce84b892c3d73c0d7b6cd6ab5a50818736ac Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Tue, 22 Sep 2026 10:40:46 -0700 Subject: [PATCH v4 2/2] Fix slotsync when logical decoding is disabled and re-enabled. Commit 6aba42c660c made slot synchronization skip persisting a new slot if logical decoding got disabled after the remote slot information was fetched. As noted in its XXX comment, the check missed the case where the last logical slot on the primary is dropped and re-created with the same name in the meantime. If the standby had replayed both the deactivation and the re-activation by then, the slot was persisted with a restart_lsn preceding the deactivation. Subsequent synchronization cycles failed with "unexpected logical decoding status change" when advancing the slot, which also stopped the synchronization of all other failover slots, and the slot could not be decoded after promotion. Fix this by remembering the end LSN of the last replayed XLOG_LOGICAL_DECODING_STATUS_CHANGE record that enables logical decoding, and by requiring the remote restart_lsn to be at or after it right after creating the local slot. Once the slot exists, a later deactivation invalidates it, so remove the check before persisting the slot. We compare the remote restart_lsn rather than the local one, so we may drop a slot that would have been usable, but the retry in the next synchronization cycle fetches fresh information. Reported-by: Nik Samokhvalov <nik@postgres.ai> Reviewed-by: shveta malik <shveta.malik@gmail.com> Reviewed-by: Nisha Moond <nisha.moond412@gmail.com> Reviewed-by: Amit Kapila <amit.kapila16@gmail.com> Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/access/transam/xlog.c | 2 +- src/backend/replication/logical/logicalctl.c | 66 +++++++++++++- src/backend/replication/logical/slotsync.c | 88 +++++++++++-------- src/include/replication/logicalctl.h | 5 +- .../recovery/t/051_effective_wal_level.pl | 79 +++++++++++++++++ 5 files changed, 201 insertions(+), 39 deletions(-) diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index 25fe4f503b3..afbe068cd0a 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -9649,7 +9649,7 @@ xlog_redo(XLogReaderState *record) * subsequent WAL records, which may not contain logical information. */ if (status) - EnableLogicalDecoding(); + EnableLogicalDecoding(lsn); else DisableLogicalDecoding(); diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index fd4ab5f7508..f0df0fabee4 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -64,6 +64,7 @@ #include "postgres.h" #include "access/xloginsert.h" +#include "access/xlogrecovery.h" #include "catalog/pg_control.h" #include "miscadmin.h" #include "replication/slot.h" @@ -95,6 +96,22 @@ typedef struct LogicalDecodingCtlData /* True if logical decoding might need to be disabled */ bool pending_disable; + + /* + * End LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record that + * enabled logical decoding, or InvalidXLogRecPtr if none has been + * replayed since the server started. Checking it with + * logical_decoding_enabled tells from which point on WAL was written with + * logical decoding enabled; see StandbyLogicalDecodingEnabledSince(). + * + * WAL records that disable logical decoding are deliberately not tracked + * here. logical_decoding_enabled is false while decoding is off, which is + * all the check needs. + * + * This is maintained only during recovery and is not persisted, so it + * says nothing about a status change replayed in an earlier server run. + */ + XLogRecPtr last_replayed_enable_lsn; } LogicalDecodingCtlData; static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; @@ -144,6 +161,7 @@ LogicalDecodingCtlShmemInit(void *arg) LogicalDecodingCtl->xlog_logical_info = false; LogicalDecodingCtl->logical_decoding_enabled = false; LogicalDecodingCtl->pending_disable = false; + LogicalDecodingCtl->last_replayed_enable_lsn = InvalidXLogRecPtr; } /* @@ -220,6 +238,35 @@ IsLogicalDecodingEnabled(void) return enabled; } +/* + * Return true if logical decoding has been enabled continuously from the given + * LSN up to the current replay position, that is, if the WAL in that range + * was written with logical decoding enabled. + * + * The given LSN must have been replayed already; nothing can be said about + * WAL this server has not replayed yet. The caller is responsible for checking + * that. + * + * A true result therefore covers only the WAL replayed so far. A deactivation + * replayed after the call still applies, and callers must arrange for that + * themselves. + */ +bool +StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn) +{ + bool result; + + Assert(RecoveryInProgress()); + Assert(lsn <= GetXLogReplayRecPtr(NULL)); + + LWLockAcquire(LogicalDecodingControlLock, LW_SHARED); + result = LogicalDecodingCtl->logical_decoding_enabled && + lsn >= LogicalDecodingCtl->last_replayed_enable_lsn; + LWLockRelease(LogicalDecodingControlLock); + + return result; +} + /* * Returns true if logical WAL logging is enabled based on the shared memory * status. @@ -340,21 +387,36 @@ EnsureLogicalDecodingEnabled(void) */ PG_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); { - EnableLogicalDecoding(); + EnableLogicalDecoding(InvalidXLogRecPtr); } PG_END_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); } /* * A workhorse function to enable logical decoding. + * + * lsn is the end LSN of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record + * being replayed, and is InvalidXLogRecPtr when not called from redo. */ void -EnableLogicalDecoding(void) +EnableLogicalDecoding(XLogRecPtr lsn) { bool in_recovery; LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Remember where logical decoding was enabled. This has to happen before + * the early return below, because replay can reach here with the status + * already on. For example, CreateCheckPoint() fixes the redo point before + * it records logicalDecodingEnabled, so a checkpoint can claim logical + * decoding is enabled while the record that enabled it still follows the + * redo point. + */ + Assert(RecoveryInProgress() == XLogRecPtrIsValid(lsn)); + if (XLogRecPtrIsValid(lsn)) + LogicalDecodingCtl->last_replayed_enable_lsn = lsn; + /* Return if it is already enabled */ if (LogicalDecodingCtl->logical_decoding_enabled) { diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index c0403893e23..0398c935a67 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -718,41 +718,6 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } - /* - * Do not persist the slot if logical decoding got disabled concurrently. - * This can happen if the last logical slot on the primary was dropped and - * the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was - * replayed after we fetched the remote slot information: WAL records - * following the slot's restart_lsn might lack the information required by - * logical decoding, and the slot invalidation performed when replaying - * the record could not find our slot as it was not created yet. - * - * It is important to perform this check after creating the slot and - * before persisting it. This way, even if the status change record is - * replayed after this check, the replay will invalidate our slot. - * - * If the check fails, we keep the temporary slot and let the caller - * retry; the next cycle fetches the remote slot information again and - * will drop this slot as the remote slot no longer exists. - * - * XXX: this check cannot detect the case where logical decoding is - * already re-enabled by a slot creation on the primary at this point. - * Detecting that would require comparing the slot's restart_lsn with the - * LSN at which logical decoding was last enabled. - */ - if (!IsLogicalDecodingEnabled()) - { - ereport(LOG, - errmsg("could not synchronize replication slot \"%s\"", - remote_slot->name), - errdetail("Logical decoding was concurrently disabled.")); - - if (slot_persistence_pending) - *slot_persistence_pending = true; - - return false; - } - ReplicationSlotPersist(); ereport(LOG, @@ -883,6 +848,7 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, { NameData plugin_name; TransactionId xmin_horizon = InvalidTransactionId; + XLogRecPtr replay_lsn; /* Skip creating the local slot if remote_slot is invalidated already */ if (remote_slot->invalidated != RS_INVAL_NONE) @@ -901,6 +867,58 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, remote_slot->failover, true); + /* + * The remote slot information can predate a status change record that + * this standby has already replayed. That happens when the last + * logical slot on the primary is dropped, and possibly re-created + * with the same name, after fetch_remote_slots() ran. The resulting + * deactivation could not invalidate our slot because it did not exist + * yet, and WAL following the (stale) remote restart_lsn may lack the + * information logical decoding needs. Checking only whether logical + * decoding is enabled is not enough, as it can have been disabled and + * enabled again in the meantime. + * + * The check has to come after ReplicationSlotCreate(), which makes + * the slot both visible and acquired. A deactivation replayed from + * here on finds the slot in InvalidatePossiblyObsoleteSlot(), signals + * a recovery conflict and waits for the slot to be released before + * invalidating it (only in hot standby, which slot synchronization + * requires anyway). Replay therefore cannot get past that record + * behind our back, so the slot never needs to be rechecked before + * being persisted. + * + * The check only runs once replay has reached the remote restart_lsn; + * otherwise it is skipped and the slot is kept as-is. Without this, a + * standby lagging behind the primary (replay paused, or a large + * recovery_min_apply_delay) could fetch a live, valid restart_lsn + * from the primary and have it rejected by + * StandbyLogicalDecodingEnabledSince(), whose answer reflects only + * WAL replayed so far and says nothing about an LSN replay hasn't + * reached yet. That would drop a perfectly good slot every cycle. + * + * Even so, the comparison uses the remote restart_lsn rather than the + * local one, so a slot that would have been usable may be dropped; + * the next cycle fetches fresh information. The slot cannot be kept, + * as it would go on using the stale restart_lsn. + */ + replay_lsn = GetXLogReplayRecPtr(NULL); + if (remote_slot->restart_lsn <= replay_lsn && + !StandbyLogicalDecodingEnabledSince(remote_slot->restart_lsn)) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding was disabled after the remote slot's restart LSN %X/%08X.", + LSN_FORMAT_ARGS(remote_slot->restart_lsn))); + + ReplicationSlotDropAcquired(false); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + /* For shorter lines. */ slot = MyReplicationSlot; diff --git a/src/include/replication/logicalctl.h b/src/include/replication/logicalctl.h index 0bc1302f130..97cacb02e4e 100644 --- a/src/include/replication/logicalctl.h +++ b/src/include/replication/logicalctl.h @@ -14,14 +14,17 @@ #ifndef LOGICALCTL_H #define LOGICALCTL_H +#include "access/xlogdefs.h" + extern void StartupLogicalDecodingStatus(bool last_status); extern void InitializeProcessXLogLogicalInfo(void); extern bool ProcessBarrierUpdateXLogLogicalInfo(void); extern bool IsLogicalDecodingEnabled(void); +extern bool StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn); extern bool IsXLogLogicalInfoEnabled(void); extern void AtEOXact_LogicalCtl(void); extern void EnsureLogicalDecodingEnabled(void); -extern void EnableLogicalDecoding(void); +extern void EnableLogicalDecoding(XLogRecPtr lsn); extern void RequestDisableLogicalDecoding(void); extern void DisableLogicalDecodingIfNecessary(void); extern void DisableLogicalDecoding(void); diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index b11690863d9..f153ae81828 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -598,6 +598,85 @@ select pg_sync_replication_slots(); '0', "no synced slot is left behind on standby5"); + # Test the same race, but where the slot is re-created on the primary + # before the slot synchronization resumes. Logical decoding is enabled + # again at the time the local slot is created, so checking the logical + # decoding status alone cannot tell that the remote slot information + # predates the deactivation. + + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5 for the re-creation test" + ); + + $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + + # Drop and re-create the slot, and wait for the standby to replay both + # the deactivation and the activation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + my $restart_lsn = $primary->safe_psql('postgres', + qq[select restart_lsn from pg_replication_slots where slot_name = 'sync_slot'] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got deactivated and activated again on standby5"); + + # Resume the slot synchronization. It must drop the slot created from + # the stale information, and re-create it from the re-created remote slot + # on retry. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql( + 'postgres', qq[ +select injection_points_detach('replication-slot-create-begin'); +select injection_points_wakeup('replication-slot-create-begin'); +]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot".*\n.*DETAIL: Logical decoding was disabled after the remote slot's restart LSN/, + $log_offset); + $standby5->poll_query_until('postgres', + qq[select restart_lsn >= '$restart_lsn' from pg_replication_slots where slot_name = 'sync_slot'] + ) + or die + "timed out waiting for the slot to be re-created from the re-created remote slot"; + + # The slot created on retry might not be persisted until the remote slot + # catches up with the catalog_xmin computed locally. Drop the remote slot + # to let the slot synchronization finish, keeping logical decoding enabled + # with another slot as the slot synchronization requires it. + $primary->safe_psql( + 'postgres', qq[ +select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); +select pg_drop_replication_slot('sync_slot'); +]); + $primary->wait_for_replay_catchup($standby5); + $psql_sync_slot->quit; + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot4')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5 after the re-creation test" + ); + # Test that logical slot creation on a standby fails cleanly if logical # decoding is concurrently deactivated by the end-of-recovery transition # upon promotion. -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-06 03:24  shveta malik <shveta.malik@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: shveta malik @ 2026-10-06 03:24 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers; shveta malik <shveta.malik@gmail.com>

On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> >
> > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > >
> > >
> > > I've incorporated your comment suggestions, and updated cosmetic
> > > things.Please review them.
> > >
> >
> > Hi,
> > I reviewed the TAP test and it LGTM. I found no correctness issues,
> > just a couple of nits compared to the neighboring tests. Please
> > consider these if they look okay to you:
> >
> > 1) Add the sync_slot condition to injection_points_attach() similar to
> > the neighboring tests, so the wait happens only when sync_slot itself
> > is being created.
> > 2) Add a note() after wait_for_event(), as in the other tests, so the
> > test output shows when the sync is paused at the injection point.
> >
>
> Both suggestions look good to me. I've incorporated these suggestions
> and updated the comment as discussed with Amit. I've attached the
> updated patch.
>

Sawada-san, I don't see any difference between v3 and v4, can you
please check and confirm?

thanks
Shveta






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-06 05:46  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 2 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-10-06 05:46 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Mon, Oct 5, 2026 at 8:24 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > >
> > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > >
> > > >
> > > > I've incorporated your comment suggestions, and updated cosmetic
> > > > things.Please review them.
> > > >
> > >
> > > Hi,
> > > I reviewed the TAP test and it LGTM. I found no correctness issues,
> > > just a couple of nits compared to the neighboring tests. Please
> > > consider these if they look okay to you:
> > >
> > > 1) Add the sync_slot condition to injection_points_attach() similar to
> > > the neighboring tests, so the wait happens only when sync_slot itself
> > > is being created.
> > > 2) Add a note() after wait_for_event(), as in the other tests, so the
> > > test output shows when the sync is paused at the injection point.
> > >
> >
> > Both suggestions look good to me. I've incorporated these suggestions
> > and updated the comment as discussed with Amit. I've attached the
> > updated patch.
> >
>
> Sawada-san, I don't see any difference between v3 and v4, can you
> please check and confirm?

Oops, sorry I forgot to include the changes to the patches when doing
git format-patch. I've attached the correct one.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments: download all (2 files, .tar.gz)

v5-0001-Add-an-init-callback-for-the-logical-decoding-con.patch (text/x-patch, 1.9K) download From 1ae2fda354de41503caf030b15bf17bec9ec86a9 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Fri, 25 Sep 2026 10:45:37 -0700 Subject: [PATCH v5 1/2] Add an init callback for the logical decoding control data. LogicalDecodingCtl had no init callback so there is no guarantee that its fields are initialized. Its startup function StartupLogicalDecodingStatus() also returns wihtout touching the fields when wal_level is 'minimal'. Intialize them in an init callback explcitly. This is not a bug fix but we just shouldn't be depending on the allocator by accident. Backpatch to v19, where logicalctl.c was introduced. Reviewed-by: Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/replication/logical/logicalctl.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index 642d965bd1c..fd4ab5f7508 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -100,9 +100,11 @@ typedef struct LogicalDecodingCtlData static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; static void LogicalDecodingCtlShmemRequest(void *arg); +static void LogicalDecodingCtlShmemInit(void *arg); const ShmemCallbacks LogicalDecodingCtlShmemCallbacks = { .request_fn = LogicalDecodingCtlShmemRequest, + .init_fn = LogicalDecodingCtlShmemInit, }; /* @@ -136,6 +138,14 @@ LogicalDecodingCtlShmemRequest(void *arg) ); } +static void +LogicalDecodingCtlShmemInit(void *arg) +{ + LogicalDecodingCtl->xlog_logical_info = false; + LogicalDecodingCtl->logical_decoding_enabled = false; + LogicalDecodingCtl->pending_disable = false; +} + /* * Initialize the logical decoding status in shmem at server startup. This * must be called ONCE during postmaster or standalone-backend startup. -- 2.55.0
v5-0002-Fix-slotsync-when-logical-decoding-is-disabled-an.patch (text/x-patch, 16.5K) download From eb381bb1537e1791f590e67d8bb823f1498f7b01 Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Tue, 22 Sep 2026 10:40:46 -0700 Subject: [PATCH v5 2/2] Fix slotsync when logical decoding is disabled and re-enabled. Commit 6aba42c660c made slot synchronization skip persisting a new slot if logical decoding got disabled after the remote slot information was fetched. As noted in its XXX comment, the check missed the case where the last logical slot on the primary is dropped and re-created with the same name in the meantime. If the standby had replayed both the deactivation and the re-activation by then, the slot was persisted with a restart_lsn preceding the deactivation. Subsequent synchronization cycles failed with "unexpected logical decoding status change" when advancing the slot, which also stopped the synchronization of all other failover slots, and the slot could not be decoded after promotion. Fix this by remembering the end LSN of the last replayed XLOG_LOGICAL_DECODING_STATUS_CHANGE record that enables logical decoding, and by requiring the remote restart_lsn to be at or after it right after creating the local slot. Once the slot exists, a later deactivation invalidates it, so remove the check before persisting the slot. We compare the remote restart_lsn rather than the local one, so we may drop a slot that would have been usable, but the retry in the next synchronization cycle fetches fresh information. Reported-by: Nik Samokhvalov <nik@postgres.ai> Reviewed-by: shveta malik <shveta.malik@gmail.com> Reviewed-by: Nisha Moond <nisha.moond412@gmail.com> Reviewed-by: Amit Kapila <amit.kapila16@gmail.com> Discussion: https://postgr.es/m/CAM527d_eV_BAYFiQnfZLSPfHoihye=nOi-OnAM_57pdH+F+gfA@mail.gmail.com Backpatch-through: 19 --- src/backend/access/transam/xlog.c | 2 +- src/backend/replication/logical/logicalctl.c | 62 ++++++++++++- src/backend/replication/logical/slotsync.c | 93 ++++++++++++------- src/include/replication/logicalctl.h | 5 +- .../recovery/t/051_effective_wal_level.pl | 80 ++++++++++++++++ 5 files changed, 203 insertions(+), 39 deletions(-) diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index 25fe4f503b3..afbe068cd0a 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -9649,7 +9649,7 @@ xlog_redo(XLogReaderState *record) * subsequent WAL records, which may not contain logical information. */ if (status) - EnableLogicalDecoding(); + EnableLogicalDecoding(lsn); else DisableLogicalDecoding(); diff --git a/src/backend/replication/logical/logicalctl.c b/src/backend/replication/logical/logicalctl.c index fd4ab5f7508..d076ff65f88 100644 --- a/src/backend/replication/logical/logicalctl.c +++ b/src/backend/replication/logical/logicalctl.c @@ -64,6 +64,7 @@ #include "postgres.h" #include "access/xloginsert.h" +#include "access/xlogrecovery.h" #include "catalog/pg_control.h" #include "miscadmin.h" #include "replication/slot.h" @@ -95,6 +96,22 @@ typedef struct LogicalDecodingCtlData /* True if logical decoding might need to be disabled */ bool pending_disable; + + /* + * End LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record that + * enabled logical decoding, or InvalidXLogRecPtr if none has been + * replayed since the server started. Checking it with + * logical_decoding_enabled tells from which point on WAL was written with + * logical decoding enabled; see StandbyLogicalDecodingEnabledSince(). + * + * WAL records that disable logical decoding are deliberately not tracked + * here. logical_decoding_enabled is false while decoding is off, which is + * all the check needs. + * + * This is maintained only during recovery and is not persisted, so it + * says nothing about a status change replayed in an earlier server run. + */ + XLogRecPtr last_replayed_enable_lsn; } LogicalDecodingCtlData; static LogicalDecodingCtlData *LogicalDecodingCtl = NULL; @@ -144,6 +161,7 @@ LogicalDecodingCtlShmemInit(void *arg) LogicalDecodingCtl->xlog_logical_info = false; LogicalDecodingCtl->logical_decoding_enabled = false; LogicalDecodingCtl->pending_disable = false; + LogicalDecodingCtl->last_replayed_enable_lsn = InvalidXLogRecPtr; } /* @@ -220,6 +238,31 @@ IsLogicalDecodingEnabled(void) return enabled; } +/* + * Return true if logical decoding has been enabled continuously from the given + * LSN up to the current replay position, that is, if the WAL in that range + * was written with logical decoding enabled. + * + * The given LSN must have been replayed already; nothing can be said about + * WAL this server has not replayed yet. The caller is responsible for checking + * that. + */ +bool +StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn) +{ + bool result; + + Assert(RecoveryInProgress()); + Assert(lsn <= GetXLogReplayRecPtr(NULL)); + + LWLockAcquire(LogicalDecodingControlLock, LW_SHARED); + result = LogicalDecodingCtl->logical_decoding_enabled && + lsn >= LogicalDecodingCtl->last_replayed_enable_lsn; + LWLockRelease(LogicalDecodingControlLock); + + return result; +} + /* * Returns true if logical WAL logging is enabled based on the shared memory * status. @@ -340,21 +383,36 @@ EnsureLogicalDecodingEnabled(void) */ PG_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); { - EnableLogicalDecoding(); + EnableLogicalDecoding(InvalidXLogRecPtr); } PG_END_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0); } /* * A workhorse function to enable logical decoding. + * + * lsn is the end LSN of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record + * being replayed, and is InvalidXLogRecPtr when not called from redo. */ void -EnableLogicalDecoding(void) +EnableLogicalDecoding(XLogRecPtr lsn) { bool in_recovery; LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE); + /* + * Remember where logical decoding was enabled. This has to happen before + * the early return below, because replay can reach here with the status + * already on. For example, CreateCheckPoint() fixes the redo point before + * it records logicalDecodingEnabled, so a checkpoint can claim logical + * decoding is enabled while the record that enabled it still follows the + * redo point. + */ + Assert(RecoveryInProgress() == XLogRecPtrIsValid(lsn)); + if (XLogRecPtrIsValid(lsn)) + LogicalDecodingCtl->last_replayed_enable_lsn = lsn; + /* Return if it is already enabled */ if (LogicalDecodingCtl->logical_decoding_enabled) { diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c index c0403893e23..efea6705bc1 100644 --- a/src/backend/replication/logical/slotsync.c +++ b/src/backend/replication/logical/slotsync.c @@ -718,41 +718,6 @@ update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, return false; } - /* - * Do not persist the slot if logical decoding got disabled concurrently. - * This can happen if the last logical slot on the primary was dropped and - * the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was - * replayed after we fetched the remote slot information: WAL records - * following the slot's restart_lsn might lack the information required by - * logical decoding, and the slot invalidation performed when replaying - * the record could not find our slot as it was not created yet. - * - * It is important to perform this check after creating the slot and - * before persisting it. This way, even if the status change record is - * replayed after this check, the replay will invalidate our slot. - * - * If the check fails, we keep the temporary slot and let the caller - * retry; the next cycle fetches the remote slot information again and - * will drop this slot as the remote slot no longer exists. - * - * XXX: this check cannot detect the case where logical decoding is - * already re-enabled by a slot creation on the primary at this point. - * Detecting that would require comparing the slot's restart_lsn with the - * LSN at which logical decoding was last enabled. - */ - if (!IsLogicalDecodingEnabled()) - { - ereport(LOG, - errmsg("could not synchronize replication slot \"%s\"", - remote_slot->name), - errdetail("Logical decoding was concurrently disabled.")); - - if (slot_persistence_pending) - *slot_persistence_pending = true; - - return false; - } - ReplicationSlotPersist(); ereport(LOG, @@ -883,6 +848,7 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, { NameData plugin_name; TransactionId xmin_horizon = InvalidTransactionId; + XLogRecPtr replay_lsn; /* Skip creating the local slot if remote_slot is invalidated already */ if (remote_slot->invalidated != RS_INVAL_NONE) @@ -901,6 +867,63 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, remote_slot->failover, true); + /* + * The remote slot information can predate a status change record that + * this standby has already replayed. That happens when the last + * logical slot on the primary is dropped, and possibly re-created + * with the same name, after fetch_remote_slots() ran. The resulting + * deactivation could not invalidate our slot because it did not exist + * yet, and WAL following the (stale) remote restart_lsn may lack the + * information logical decoding needs. Checking only whether logical + * decoding is enabled is not enough, as it can have been disabled and + * enabled again in the meantime. + * + * The check has to come after ReplicationSlotCreate(), which makes + * the slot both visible and acquired. A deactivation replayed from + * here on finds the slot in InvalidatePossiblyObsoleteSlot(), signals + * a recovery conflict and waits for the slot to be released before + * invalidating it (only in hot standby, which slot synchronization + * requires anyway). Replay therefore cannot get past that record + * behind our back, so the slot never needs to be rechecked before + * being persisted. + * + * The check only runs once replay has reached the remote restart_lsn; + * otherwise it is skipped and the slot is kept as-is. Without this, a + * standby lagging behind the primary (replay paused, or a large + * recovery_min_apply_delay) could fetch a live, valid restart_lsn + * from the primary and have it rejected by + * StandbyLogicalDecodingEnabledSince(), whose answer reflects only + * WAL replayed so far and says nothing about an LSN replay hasn't + * reached yet. That would drop a perfectly good slot every cycle. + * Skipping the check is safe: only a deactivation at or after the + * remote restart_lsn can leave the WAL that follows it without the + * information logical decoding needs, and replay has not reached such + * a record yet. Replaying it later invalidates the slot whether or + * not it has been persisted by then. + * + * Even so, the comparison uses the remote restart_lsn rather than the + * local one, so a slot that would have been usable may be dropped; + * the next cycle fetches fresh information. The slot cannot be kept, + * as it would go on using the stale restart_lsn. + */ + replay_lsn = GetXLogReplayRecPtr(NULL); + if (remote_slot->restart_lsn <= replay_lsn && + !StandbyLogicalDecodingEnabledSince(remote_slot->restart_lsn)) + { + ereport(LOG, + errmsg("could not synchronize replication slot \"%s\"", + remote_slot->name), + errdetail("Logical decoding was disabled after the remote slot's restart LSN %X/%08X.", + LSN_FORMAT_ARGS(remote_slot->restart_lsn))); + + ReplicationSlotDropAcquired(false); + + if (slot_persistence_pending) + *slot_persistence_pending = true; + + return false; + } + /* For shorter lines. */ slot = MyReplicationSlot; diff --git a/src/include/replication/logicalctl.h b/src/include/replication/logicalctl.h index 0bc1302f130..97cacb02e4e 100644 --- a/src/include/replication/logicalctl.h +++ b/src/include/replication/logicalctl.h @@ -14,14 +14,17 @@ #ifndef LOGICALCTL_H #define LOGICALCTL_H +#include "access/xlogdefs.h" + extern void StartupLogicalDecodingStatus(bool last_status); extern void InitializeProcessXLogLogicalInfo(void); extern bool ProcessBarrierUpdateXLogLogicalInfo(void); extern bool IsLogicalDecodingEnabled(void); +extern bool StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn); extern bool IsXLogLogicalInfoEnabled(void); extern void AtEOXact_LogicalCtl(void); extern void EnsureLogicalDecodingEnabled(void); -extern void EnableLogicalDecoding(void); +extern void EnableLogicalDecoding(XLogRecPtr lsn); extern void RequestDisableLogicalDecoding(void); extern void DisableLogicalDecodingIfNecessary(void); extern void DisableLogicalDecoding(void); diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index b11690863d9..8e79f9f6866 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -598,6 +598,86 @@ select pg_sync_replication_slots(); '0', "no synced slot is left behind on standby5"); + # Test the same race, but where the slot is re-created on the primary + # before the slot synchronization resumes. Logical decoding is enabled + # again at the time the local slot is created, so checking the logical + # decoding status alone cannot tell that the remote slot information + # predates the deactivation. + + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got activated on standby5 for the re-creation test" + ); + + $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot->query_until( + qr/sync_slots/, + q(\echo sync_slots +select injection_points_set_local(); +select injection_points_attach('replication-slot-create-begin', 'wait', 'sync_slot'); +select pg_sync_replication_slots(); +)); + $standby5->wait_for_event('client backend', + 'replication-slot-create-begin'); + note("injection_point 'replication-slot-create-begin' is reached"); + + # Drop and re-create the slot, and wait for the standby to replay both + # the deactivation and the activation. + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('sync_slot')]); + wait_for_logical_decoding_disabled($primary); + $primary->safe_psql('postgres', + qq[select pg_create_logical_replication_slot('sync_slot', 'test_decoding', false, false, true)] + ); + my $restart_lsn = $primary->safe_psql('postgres', + qq[select restart_lsn from pg_replication_slots where slot_name = 'sync_slot'] + ); + $primary->wait_for_replay_catchup($standby5); + test_wal_level($standby5, "replica|logical", + "logical decoding got deactivated and activated again on standby5"); + + # Resume the slot synchronization. It must drop the slot created from + # the stale information, and re-create it from the re-created remote slot + # on retry. + $log_offset = -s $standby5->logfile; + $standby5->safe_psql( + 'postgres', qq[ +select injection_points_detach('replication-slot-create-begin'); +select injection_points_wakeup('replication-slot-create-begin'); +]); + $standby5->wait_for_log( + qr/could not synchronize replication slot "sync_slot".*\n.*DETAIL: Logical decoding was disabled after the remote slot's restart LSN/, + $log_offset); + $standby5->poll_query_until('postgres', + qq[select restart_lsn >= '$restart_lsn' from pg_replication_slots where slot_name = 'sync_slot'] + ) + or die + "timed out waiting for the slot to be re-created from the re-created remote slot"; + + # The slot created on retry might not be persisted until the remote slot + # catches up with the catalog_xmin computed locally. Drop the remote slot + # to let the slot synchronization finish, keeping logical decoding enabled + # with another slot as the slot synchronization requires it. + $primary->safe_psql( + 'postgres', qq[ +select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); +select pg_drop_replication_slot('sync_slot'); +]); + $primary->wait_for_replay_catchup($standby5); + $psql_sync_slot->quit; + $primary->safe_psql('postgres', + qq[select pg_drop_replication_slot('test_slot4')]); + wait_for_logical_decoding_disabled($primary); + $primary->wait_for_replay_catchup($standby5); + is( $standby5->safe_psql( + 'postgres', qq[select count(*) from pg_replication_slots]), + '0', + "no synced slot is left behind on standby5 after the re-creation test" + ); + # Test that logical slot creation on a standby fails cleanly if logical # decoding is concurrently deactivated by the end-of-recovery transition # upon promotion. -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-07 02:52  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 0 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-10-07 02:52 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Mon, Oct 5, 2026 at 10:46 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Mon, Oct 5, 2026 at 8:24 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > >
> > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > > >
> > > > >
> > > > > I've incorporated your comment suggestions, and updated cosmetic
> > > > > things.Please review them.
> > > > >
> > > >
> > > > Hi,
> > > > I reviewed the TAP test and it LGTM. I found no correctness issues,
> > > > just a couple of nits compared to the neighboring tests. Please
> > > > consider these if they look okay to you:
> > > >
> > > > 1) Add the sync_slot condition to injection_points_attach() similar to
> > > > the neighboring tests, so the wait happens only when sync_slot itself
> > > > is being created.
> > > > 2) Add a note() after wait_for_event(), as in the other tests, so the
> > > > test output shows when the sync is paused at the injection point.
> > > >
> > >
> > > Both suggestions look good to me. I've incorporated these suggestions
> > > and updated the comment as discussed with Amit. I've attached the
> > > updated patch.
> > >
> >
> > Sawada-san, I don't see any difference between v3 and v4, can you
> > please check and confirm?
>
> Oops, sorry I forgot to include the changes to the patches when doing
> git format-patch. I've attached the correct one.
>

I'm going to push them tomorrow, barring objections.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-07 03:43  shveta malik <shveta.malik@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 1 reply; 59+ messages in thread

From: shveta malik @ 2026-10-07 03:43 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers; shveta malik <shveta.malik@gmail.com>

On Tue, Oct 6, 2026 at 11:16 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Mon, Oct 5, 2026 at 8:24 PM shveta malik <shveta.malik@gmail.com> wrote:
> >
> > On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > >
> > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > >
> > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > > >
> > > > >
> > > > > I've incorporated your comment suggestions, and updated cosmetic
> > > > > things.Please review them.
> > > > >
> > > >
> > > > Hi,
> > > > I reviewed the TAP test and it LGTM. I found no correctness issues,
> > > > just a couple of nits compared to the neighboring tests. Please
> > > > consider these if they look okay to you:
> > > >
> > > > 1) Add the sync_slot condition to injection_points_attach() similar to
> > > > the neighboring tests, so the wait happens only when sync_slot itself
> > > > is being created.
> > > > 2) Add a note() after wait_for_event(), as in the other tests, so the
> > > > test output shows when the sync is paused at the injection point.
> > > >
> > >
> > > Both suggestions look good to me. I've incorporated these suggestions
> > > and updated the comment as discussed with Amit. I've attached the
> > > updated patch.
> > >
> >
> > Sawada-san, I don't see any difference between v3 and v4, can you
> > please check and confirm?
>
> Oops, sorry I forgot to include the changes to the patches when doing
> git format-patch. I've attached the correct one.
>

Thanks, the patches LGTM.

thanks
Shveta






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-07 19:07  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-10-07 19:07 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Tue, Oct 6, 2026 at 8:43 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Tue, Oct 6, 2026 at 11:16 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > On Mon, Oct 5, 2026 at 8:24 PM shveta malik <shveta.malik@gmail.com> wrote:
> > >
> > > On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > >
> > > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond <nisha.moond412@gmail.com> wrote:
> > > > >
> > > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > > > >
> > > > > >
> > > > > > I've incorporated your comment suggestions, and updated cosmetic
> > > > > > things.Please review them.
> > > > > >
> > > > >
> > > > > Hi,
> > > > > I reviewed the TAP test and it LGTM. I found no correctness issues,
> > > > > just a couple of nits compared to the neighboring tests. Please
> > > > > consider these if they look okay to you:
> > > > >
> > > > > 1) Add the sync_slot condition to injection_points_attach() similar to
> > > > > the neighboring tests, so the wait happens only when sync_slot itself
> > > > > is being created.
> > > > > 2) Add a note() after wait_for_event(), as in the other tests, so the
> > > > > test output shows when the sync is paused at the injection point.
> > > > >
> > > >
> > > > Both suggestions look good to me. I've incorporated these suggestions
> > > > and updated the comment as discussed with Amit. I've attached the
> > > > updated patch.
> > > >
> > >
> > > Sawada-san, I don't see any difference between v3 and v4, can you
> > > please check and confirm?
> >
> > Oops, sorry I forgot to include the changes to the patches when doing
> > git format-patch. I've attached the correct one.
> >
>
> Thanks, the patches LGTM.

Pushed.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-08 00:33  Fujii Masao <masao.fujii@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Fujii Masao @ 2026-10-08 00:33 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> Pushed.

The buildfarm member skink reported a failure in the test added by commit
1f2245371e3 [1].

[23:05:02.489](9.575s) not ok 45 - no synced slot is left behind on
standby5 after the re-creation test
[23:05:02.489](0.000s) #   Failed test 'no synced slot is left behind
on standby5 after the re-creation test'

The test expects the standby's synced slot to disappear after the
corresponding slot is dropped on the primary. But, in the failed test
case, the test found one slot instead of zero.

The slot can become persistent before the primary drops it. In that case,
WAL replay invalidates the standby slot but does not remove it, leaving one
slot behind. This seems to explain the slot-count failure.

To address this, how about running pg_sync_replication_slots() once more
as follows? This extra sync cycle removes the obsolete slot.

  $primary->wait_for_replay_catchup($standby5);
  $psql_sync_slot->quit;
+ # The slot may have become sync-ready before it was dropped on the
+ # primary.  In that case, replay invalidates it, and a new sync cycle
+ # must remove it from the standby.
+ $standby5->safe_psql('postgres',
+ qq[select pg_sync_replication_slots()]);
  $primary->safe_psql('postgres',
  qq[select pg_drop_replication_slot('test_slot4')]);
  wait_for_logical_decoding_disabled($primary);

Regards,

[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2026-10-07%2019%3A44%3A45

-- 
Fujii Masao






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-08 01:09  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Fujii Masao <masao.fujii@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-10-08 01:09 UTC (permalink / raw)
  To: Fujii Masao <masao.fujii@gmail.com>; +Cc: shveta malik <shveta.malik@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Wed, Oct 7, 2026 at 5:33 PM Fujii Masao <masao.fujii@gmail.com> wrote:
>
> On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > Pushed.
>
> The buildfarm member skink reported a failure in the test added by commit
> 1f2245371e3 [1].
>
> [23:05:02.489](9.575s) not ok 45 - no synced slot is left behind on
> standby5 after the re-creation test
> [23:05:02.489](0.000s) #   Failed test 'no synced slot is left behind
> on standby5 after the re-creation test'
>
> The test expects the standby's synced slot to disappear after the
> corresponding slot is dropped on the primary. But, in the failed test
> case, the test found one slot instead of zero.
>
> The slot can become persistent before the primary drops it. In that case,
> WAL replay invalidates the standby slot but does not remove it, leaving one
> slot behind. This seems to explain the slot-count failure.

Right. The sync_slot was created on the standby from the re-created
remote slot as we expect, but it then became sync-ready in the same
pg_sync_replication_slots() call. I expected that after detecting the
disable/re-enable, the retry would re-create the slot but not be able
to persist it because the standby's xmin
is ahead of the remote slot's. But that's not necessarily true.

> To address this, how about running pg_sync_replication_slots() once more
> as follows? This extra sync cycle removes the obsolete slot.
>
>   $primary->wait_for_replay_catchup($standby5);
>   $psql_sync_slot->quit;
> + # The slot may have become sync-ready before it was dropped on the
> + # primary.  In that case, replay invalidates it, and a new sync cycle
> + # must remove it from the standby.
> + $standby5->safe_psql('postgres',
> + qq[select pg_sync_replication_slots()]);
>   $primary->safe_psql('postgres',
>   qq[select pg_drop_replication_slot('test_slot4')]);
>   wait_for_logical_decoding_disabled($primary);

I agree that it's a reasonable fix. This can handle both cases where
the synced slot is persistent and not persistent: if the synced slot
was persisted, drop_local_obsolete_slots() removes it now that the
remote slot is gone, and if it stayed temporary it has already been
removed by the time the background session finished, so the extra call
is just a no-op.

Another option would be to make it deterministic the other way around:
advance the remote slot on the primary until the synced slot becomes
sync-ready, then clean up. That's what
040_standby_failover_slots_sync.pl does for its retry case, but there
the subscription keeps consuming the remote slot for us. Nothing
consumes sync_slot here, so we would need a loop calling
pg_log_standby_snapshot() and pg_logical_slot_get_changes() until the
slot is persisted. I prefer Fujii-san's approach.

I've attached the patch.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Attachments:

v1-0001-Stabilize-recently-added-tests-in-051_effective_w.patch (text/x-patch, 2.9K) download From 05c0d2e5a6b2c78a1b7535513cd092e67ea0086e Mon Sep 17 00:00:00 2001 From: Masahiko Sawada <sawada.mshk@gmail.com> Date: Wed, 7 Oct 2026 17:51:53 -0700 Subject: [PATCH v1] Stabilize recently added tests in 051_effective_wal_level.pl. Commit 1f2245371e3 added a test for the case where logical decoding is disabled and re-enabled while synchronizing a replication slot. Its cleanup assumed the slot re-created on retry would still be temporary, and so would be gone once the corresponding remote slot was dropped. That isn't guaranteed: the catalog_xmin reserved on the standby is not necessarily ahead of the remote slot's. In that case the slot is persisted on the first retry, and the subsequent logical decoding deactivation invalidates it on the standby rather than dropping it, so the check that no synced slot is left behind fails. Stabilize the cleanup by calling an extra pg_sync_replication_slots() after dropping the remote slot and before disabling logical decoding on the primary. Per buildfarm member skink. Reported-by: Fujii Masao <masao.fujii@gmail.com> Suggsted-by: Fujii Masao <masao.fujii@gmail.com> Reviewed-by: Discussion: https://postgr.es/m/CAHGQGwFWXASACRnhHJgEdk8nWyLw4bLLDhiEiKSqBqd+tzJ2Pg@mail.gmail.com Backpatch-through: 19 --- src/test/recovery/t/051_effective_wal_level.pl | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 3b70a0722a9..4aa26ec786b 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -687,10 +687,9 @@ select injection_points_wakeup('replication-slot-create-begin'); or die "timed out waiting for the slot to be re-created from the re-created remote slot"; - # The slot created on retry might not be persisted until the remote slot - # catches up with the catalog_xmin computed locally. Drop the remote slot - # to let the slot synchronization finish, keeping logical decoding enabled - # with another slot as the slot synchronization requires it. + # Drop the remote slot so that the slot synchronization has nothing left + # to retry, keeping logical decoding enabled with another slot as the + # slot synchronization requires it. $primary->safe_psql( 'postgres', qq[ select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); @@ -698,6 +697,12 @@ select pg_drop_replication_slot('sync_slot'); ]); $primary->wait_for_replay_catchup($standby5); $psql_sync_slot->quit; + + # The slot created on retry may or may not have been persisted by the + # time the remote slot was dropped. One more synchronization cycle + # drops the local slot either way. + $standby5->safe_psql('postgres', qq[select pg_sync_replication_slots()]); + $primary->safe_psql('postgres', qq[select pg_drop_replication_slot('test_slot4')]); wait_for_logical_decoding_disabled($primary); -- 2.55.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-08 03:25  shveta malik <shveta.malik@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: shveta malik @ 2026-10-08 03:25 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Fujii Masao <masao.fujii@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers; shveta malik <shveta.malik@gmail.com>

On Thu, Oct 8, 2026 at 6:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Wed, Oct 7, 2026 at 5:33 PM Fujii Masao <masao.fujii@gmail.com> wrote:
> >
> > On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > Pushed.
> >
> > The buildfarm member skink reported a failure in the test added by commit
> > 1f2245371e3 [1].
> >
> > [23:05:02.489](9.575s) not ok 45 - no synced slot is left behind on
> > standby5 after the re-creation test
> > [23:05:02.489](0.000s) #   Failed test 'no synced slot is left behind
> > on standby5 after the re-creation test'
> >
> > The test expects the standby's synced slot to disappear after the
> > corresponding slot is dropped on the primary. But, in the failed test
> > case, the test found one slot instead of zero.
> >
> > The slot can become persistent before the primary drops it. In that case,
> > WAL replay invalidates the standby slot but does not remove it, leaving one
> > slot behind. This seems to explain the slot-count failure.
>
> Right. The sync_slot was created on the standby from the re-created
> remote slot as we expect, but it then became sync-ready in the same
> pg_sync_replication_slots() call. I expected that after detecting the
> disable/re-enable, the retry would re-create the slot but not be able
> to persist it because the standby's xmin
> is ahead of the remote slot's. But that's not necessarily true.
>
> > To address this, how about running pg_sync_replication_slots() once more
> > as follows? This extra sync cycle removes the obsolete slot.
> >
> >   $primary->wait_for_replay_catchup($standby5);
> >   $psql_sync_slot->quit;
> > + # The slot may have become sync-ready before it was dropped on the
> > + # primary.  In that case, replay invalidates it, and a new sync cycle
> > + # must remove it from the standby.
> > + $standby5->safe_psql('postgres',
> > + qq[select pg_sync_replication_slots()]);
> >   $primary->safe_psql('postgres',
> >   qq[select pg_drop_replication_slot('test_slot4')]);
> >   wait_for_logical_decoding_disabled($primary);
>
> I agree that it's a reasonable fix. This can handle both cases where
> the synced slot is persistent and not persistent: if the synced slot
> was persisted, drop_local_obsolete_slots() removes it now that the
> remote slot is gone, and if it stayed temporary it has already been
> removed by the time the background session finished, so the extra call
> is just a no-op.

+1

> Another option would be to make it deterministic the other way around:
> advance the remote slot on the primary until the synced slot becomes
> sync-ready, then clean up. That's what
> 040_standby_failover_slots_sync.pl does for its retry case, but there
> the subscription keeps consuming the remote slot for us. Nothing
> consumes sync_slot here, so we would need a loop calling
> pg_log_standby_snapshot() and pg_logical_slot_get_changes() until the
> slot is persisted. I prefer Fujii-san's approach.

I too prefer Fujii-san's approach.

> I've attached the patch.

LGTM.

thanks
Shveta






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-08 18:27  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: shveta malik <shveta.malik@gmail.com>
  0 siblings, 0 replies; 59+ messages in thread

From: Masahiko Sawada @ 2026-10-08 18:27 UTC (permalink / raw)
  To: shveta malik <shveta.malik@gmail.com>; +Cc: Fujii Masao <masao.fujii@gmail.com>; Nisha Moond <nisha.moond412@gmail.com>; Nikolay Samokhvalov <nik@postgres.ai>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Wed, Oct 7, 2026 at 8:26 PM shveta malik <shveta.malik@gmail.com> wrote:
>
> On Thu, Oct 8, 2026 at 6:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > On Wed, Oct 7, 2026 at 5:33 PM Fujii Masao <masao.fujii@gmail.com> wrote:
> > >
> > > On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > > Pushed.
> > >
> > > The buildfarm member skink reported a failure in the test added by commit
> > > 1f2245371e3 [1].
> > >
> > > [23:05:02.489](9.575s) not ok 45 - no synced slot is left behind on
> > > standby5 after the re-creation test
> > > [23:05:02.489](0.000s) #   Failed test 'no synced slot is left behind
> > > on standby5 after the re-creation test'
> > >
> > > The test expects the standby's synced slot to disappear after the
> > > corresponding slot is dropped on the primary. But, in the failed test
> > > case, the test found one slot instead of zero.
> > >
> > > The slot can become persistent before the primary drops it. In that case,
> > > WAL replay invalidates the standby slot but does not remove it, leaving one
> > > slot behind. This seems to explain the slot-count failure.
> >
> > Right. The sync_slot was created on the standby from the re-created
> > remote slot as we expect, but it then became sync-ready in the same
> > pg_sync_replication_slots() call. I expected that after detecting the
> > disable/re-enable, the retry would re-create the slot but not be able
> > to persist it because the standby's xmin
> > is ahead of the remote slot's. But that's not necessarily true.
> >
> > > To address this, how about running pg_sync_replication_slots() once more
> > > as follows? This extra sync cycle removes the obsolete slot.
> > >
> > >   $primary->wait_for_replay_catchup($standby5);
> > >   $psql_sync_slot->quit;
> > > + # The slot may have become sync-ready before it was dropped on the
> > > + # primary.  In that case, replay invalidates it, and a new sync cycle
> > > + # must remove it from the standby.
> > > + $standby5->safe_psql('postgres',
> > > + qq[select pg_sync_replication_slots()]);
> > >   $primary->safe_psql('postgres',
> > >   qq[select pg_drop_replication_slot('test_slot4')]);
> > >   wait_for_logical_decoding_disabled($primary);
> >
> > I agree that it's a reasonable fix. This can handle both cases where
> > the synced slot is persistent and not persistent: if the synced slot
> > was persisted, drop_local_obsolete_slots() removes it now that the
> > remote slot is gone, and if it stayed temporary it has already been
> > removed by the time the background session finished, so the extra call
> > is just a no-op.
>
> +1
>
> > Another option would be to make it deterministic the other way around:
> > advance the remote slot on the primary until the synced slot becomes
> > sync-ready, then clean up. That's what
> > 040_standby_failover_slots_sync.pl does for its retry case, but there
> > the subscription keeps consuming the remote slot for us. Nothing
> > consumes sync_slot here, so we would need a loop calling
> > pg_log_standby_snapshot() and pg_logical_slot_get_changes() until the
> > slot is persisted. I prefer Fujii-san's approach.
>
> I too prefer Fujii-san's approach.
>
> > I've attached the patch.
>
> LGTM.

Thank you for reviewing the patch! Pushed.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-30 08:00  Alexander Lakhin <exclusion@gmail.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  1 sibling, 1 reply; 59+ messages in thread

From: Alexander Lakhin @ 2026-10-30 08:00 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Hello Sawada-san,

31.07.2026 06:49, Masahiko Sawada wrote:
> What does the buildfarm member produce the above logs? Many buildfarm
> members failed with that error due to commit 6a80179f6b0, but I've not
> seen further failures since pushing commit 18f9785e0b3.

It took 3 months for buildfarm animals to discover an instability of the
fixed test:
[03:38:56.925](0.036s) # injection_point 'logical-decoding-activation' is reached
[03:38:56.997](0.072s) ok 37 - the activation process aborted
[03:38:57.013](0.016s) # connect output:
# {
#   'stderr' => 'background_psql: ready
# ',
#   'stdout' => 'background_psql: ready
# '
# }
[03:42:33.612](216.599s) # poll_query_until timed out executing this query:
#
#         SELECT count(*) > 0 FROM pg_stat_activity
#         WHERE backend_type = 'client backend' AND wait_event = 'logical-decoding-activation'
#
# expecting this output:
# t
# last actual query output:
# f
# with stderr:
[03:42:33.613](0.000s) # die: timed out when waiting for client backend to reach wait event 
'logical-decoding-activation' at /home/bf/bf-build/melonworm/HEAD/pgsql/src/test/recovery/t/051_effective_wal_level.pl 
line 515.
[03:42:33.613](0.000s) 1..37
timed out when waiting for client backend to reach wait event 'logical-decoding-activation' at 
/home/bf/bf-build/melonworm/HEAD/pgsql/src/test/recovery/t/051_effective_wal_level.pl line 515.

I can reproduce this reliably with a simple sleep:
@@ -180,6 +180,7 @@ injection_points_cleanup(int code, Datum arg)
         if (!injection_point_local)
                 return;

+pg_usleep(1000000);
         /* Detach all the local points */
         foreach(lc, inj_list_local)
         {

Could you please have a look?

`check-world` with this sleep reveals also other tests suffering from the
same disease:
src/test/modules/test_misc/t/010_index_concurrently_upsert.pl
repack_toast
repack_missingval
repack_temporal
repack_temporal_multirange

[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=melonworm&dt=2026-10-30%2002%3A36%3A29

Best regards,
Alexander

^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-30 10:33  Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  parent: Alexander Lakhin <exclusion@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Hayato Kuroda (Fujitsu) @ 2026-10-30 10:33 UTC (permalink / raw)
  To: Alexander Lakhin <exclusion@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Hi Alexander,

> It took 3 months for buildfarm animals to discover an instability of the
> fixed test:

Good catch!

> I can reproduce this reliably with a simple sleep:

I could also reproduce the same.

I found lines [1] in the publisher log, this meant that registering the point failed
because it has already been registered. Per my research, injection points which
are set as local one can also be registered on the shared memory and same local
injection points cannot be registered at the same time. set_local ensures that
the point is enabled for the specific backend and can be removed after the backend
exits. Based on that, below event can happen in the 051 test:

1. a backend registers an injection point 'logical-decoding-activation' at line 480.
2. the test runner finishes the client for the backend at line 500.
   The backend will eventually clean up the injection point, but the runner can
   go ahead without any waits.
3. the runner starts a new session immediately and tries to register the injection point.
   It could fail of the previous backend has not cleaned up yet.
4. The session can continue because on_error_stop is 0.
   It calls pg_create_logical_replication_slot() but cannot stop the injection
   point because the process does not attach.

My brief fix idea is to expressly wait until the injection point is cleaned up. See attached.

[1]
```
2026-10-30 03:38:57.014 CET [626716][client backend][3/6:0] LOG:  statement: select injection_points_set_local();
2026-10-30 03:38:57.018 CET [626716][client backend][3/7:0] LOG:  statement: select injection_points_attach('logical-decoding-activation', 'wait');
2026-10-30 03:38:57.018 CET [626716][client backend][3/7:0] ERROR:  injection point "logical-decoding-activation" already defined
2026-10-30 03:38:57.018 CET [626716][client backend][3/7:0] STATEMENT:  select injection_points_attach('logical-decoding-activation', 'wait');
```
Best regards,
Hayato Kuroda
FUJITSU LIMITED



Attachments:

add_wait.diff (application/octet-stream, 1.9K) download diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 4aa26ec786b..579d930829a 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -362,6 +362,25 @@ if ( $ENV{enable_injection_points} eq 'yes' # Test the race condition at end of the recovery between the startup and logical # decoding status change. This test requires injection points enabled. + # Wait for a local injection point to be detached during backend exit. + # BackgroundPsql::quit() waits for psql to exit, but not for the server + # backend to finish its before_shmem_exit callbacks. + sub wait_for_injection_point_detached + { + my ($node, $injection_point_name) = @_; + + $node->poll_query_until( + 'postgres', + qq[ +SELECT NOT EXISTS ( + SELECT + FROM injection_points_list() + WHERE point_name = '$injection_point_name' +)]) + or die + "timed out waiting for injection point '$injection_point_name' to be detached"; + } + # Initialize standby4 and start it. my $standby4 = PostgreSQL::Test::Cluster->new('standby4'); $standby4->init_from_backup($primary, 'my_backup', has_streaming => 1); @@ -444,6 +463,7 @@ select pg_create_logical_replication_slot('slot_1', 'test_decoding'); # Let the released backend finish creating its slot. $psql_create_slot->quit; + wait_for_injection_point_detached($primary, 'logical-decoding-activation'); # Decode from slot_2, whose start point precedes where a redundant # status-change record would have been written; this fails in xlog_decode() @@ -498,6 +518,7 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled pass("the activation process aborted"); $psql_create_slot->quit; + wait_for_injection_point_detached($primary, 'logical-decoding-activation'); # Test concurrent activation processes run and one is interrupted. $psql_create_slot =
^ permalink raw reply [nested|flat] 59+ messages in thread

* RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-30 12:37  Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  parent: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Hayato Kuroda (Fujitsu) @ 2026-10-30 12:37 UTC (permalink / raw)
  To: Alexander Lakhin <exclusion@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Masahiko Sawada <sawada.mshk@gmail.com>

Hi,

> `check-world` with this sleep reveals also other tests suffering from the
> same disease:
> src/test/modules/test_misc/t/010_index_concurrently_upsert.pl
> repack_toast
> repack_missingval
> repack_temporal
> repack_temporal_multirange

I analyzed other issues and attaches patch set. 0001 fixes the 

Regarding the isolation tests for REPACK, I observed that the requested injection
point for repack_missingval had already been registered:

```
inline patch 1: /home/hayato/builddir/testrun/injection_points/isolation/results/repack_missingval.out (+0/-2 lines) download inline-1.patch--- /home/hayato/postgres/src/test/modules/injection_points/expected/repack_missingval.out 2026-10-30 17:48:34.651557191 +0900 +++ /home/hayato/builddir/testrun/injection_points/isolation/results/repack_missingval.out 2026-10-30 19:56:22.486024917 +0900 @@ -1,38 +1,4 @@ Parsed test spec with 2 sessions starting permutation: s1_wait_before_lock s2_update s2_wakeup_before_lock s1_check -injection_points_attach ------------------------
... +setup of session s1 failed: ERROR: injection point "repack-concurrently-before-lock" already defined ``` I think the root cause is in the previous test repack_dropped.pl. It attaches the injection point but does not detach. In general, it can work because the shmem exit callback removes the point from the shared memory. But if the cleanup is delayed, the isolationtester starts a new test and the backend tries to attach the same injection point, causes the ERROR. Attached 0002 patch adds a teardown code for the test, it expressly removes the injection point. === As for the 010_update_concurrently_upsert, there is a race condition in the injection point module. When the backend calls injection_points_set_local(), it appends all attached points in inj_list_local and removes listed points at exit. Since inj_list_local is the process-local, it cannot be maintained when other backends detach the injection point. This can cause the below: 1. a backend calls injection_points_set_local() and attaches an injection point #1. 2. another backend detaches #1. 3. yet another process attaches the injection point #1. 4. initial backend exits, at that time the #1 can be removed on the shared memory. I think above race can happen in 010. 010 repeats the test that three background psql sessions are created, they attach injection points after the set_local(), run some SQL commands and ensures sessions can hit the injection point. Background sessions are quit every case but test does not wait till backends are actually exit. It's possible that registered injection points are immediately removed by exiting backends if they are delayed. This can stuck the test at ok_injection_point(). A debug log [1] allows printing whether the shmem exit callback actually detaches the injection point or not. For 010 test, every lines should be "not found" because points are expressly detached. But you can find that some injection points are detached by the cleanup function then the test can stuck because backends won't wait the injection point anymore. If we try to fix only for this test, it's enough to ensure backend processes used for the tests are exit. Attached 0003 patch implements that. But I feel it might be a fundamental issue for the injection point module. Shouldn't backends try to clean up points which is only registered by them? We can separate it from the thread based on the needs. [1] ```
inline patch 2: src/test/modules/injection_points/injection_points.c (+4/-1 lines) download inline-2.patch--- a/src/test/modules/injection_points/injection_points.c +++ b/src/test/modules/injection_points/injection_points.c @@ -180,12 +180,15 @@ injection_points_cleanup(int code, Datum arg) if (!injection_point_local) return; + pg_usleep(1000000); + /* Detach all the local points */ foreach(lc, inj_list_local) { char *name = strVal(lfirst(lc)); - (void) InjectionPointDetach(name); + elog(LOG, "detaching injection point \"%s\": %s", + name, InjectionPointDetach(name) ? "detached" : "not found"); }
``` Best regards, Hayato Kuroda FUJITSU LIMITED Patches and attachments: download all (5 files, .tar.gz)
0001-Stabilize-051_effective_wal_level.patch (application/octet-stream, 2.2K) download From b672283a5d4c7de3d8372f8d87c0fbcaed1012ab Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Fri, 30 Oct 2026 20:02:37 +0900 Subject: [PATCH 1/3] Stabilize 051_effective_wal_level --- .../recovery/t/051_effective_wal_level.pl | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 4aa26ec786b..579d930829a 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -362,6 +362,25 @@ if ( $ENV{enable_injection_points} eq 'yes' # Test the race condition at end of the recovery between the startup and logical # decoding status change. This test requires injection points enabled. + # Wait for a local injection point to be detached during backend exit. + # BackgroundPsql::quit() waits for psql to exit, but not for the server + # backend to finish its before_shmem_exit callbacks. + sub wait_for_injection_point_detached + { + my ($node, $injection_point_name) = @_; + + $node->poll_query_until( + 'postgres', + qq[ +SELECT NOT EXISTS ( + SELECT + FROM injection_points_list() + WHERE point_name = '$injection_point_name' +)]) + or die + "timed out waiting for injection point '$injection_point_name' to be detached"; + } + # Initialize standby4 and start it. my $standby4 = PostgreSQL::Test::Cluster->new('standby4'); $standby4->init_from_backup($primary, 'my_backup', has_streaming => 1); @@ -444,6 +463,7 @@ select pg_create_logical_replication_slot('slot_1', 'test_decoding'); # Let the released backend finish creating its slot. $psql_create_slot->quit; + wait_for_injection_point_detached($primary, 'logical-decoding-activation'); # Decode from slot_2, whose start point precedes where a redundant # status-change record would have been written; this fails in xlog_decode() @@ -498,6 +518,7 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled pass("the activation process aborted"); $psql_create_slot->quit; + wait_for_injection_point_detached($primary, 'logical-decoding-activation'); # Test concurrent activation processes run and one is interrupted. $psql_create_slot = -- 2.52.0
0002-Ensure-injection-point-repack-concurrently-before-lo.patch (application/octet-stream, 1.3K) download From 3585da9afaf46614166cac9090e3c43804a7b216 Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Fri, 30 Oct 2026 20:03:24 +0900 Subject: [PATCH 2/3] Ensure injection point repack-concurrently-before-lock is detached --- .../modules/injection_points/expected/repack_dropped.out | 5 +++++ src/test/modules/injection_points/specs/repack_dropped.spec | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/test/modules/injection_points/expected/repack_dropped.out b/src/test/modules/injection_points/expected/repack_dropped.out index 4186ce4981c..44ba55d94a6 100644 --- a/src/test/modules/injection_points/expected/repack_dropped.out +++ b/src/test/modules/injection_points/expected/repack_dropped.out @@ -49,3 +49,8 @@ id|fits_in_one_block 3|t (3 rows) +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack_dropped.spec b/src/test/modules/injection_points/specs/repack_dropped.spec index 8dabd4fafb4..ec888f86bbc 100644 --- a/src/test/modules/injection_points/specs/repack_dropped.spec +++ b/src/test/modules/injection_points/specs/repack_dropped.spec @@ -64,6 +64,11 @@ step s2_noop { } +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + session s3 step s3_updates { -- 2.52.0
0003-Stabilize-010_index_concurrently_upsert.patch (application/octet-stream, 6.1K) download From cf8acadbd94b165ac834f0f382235820aa5699b0 Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Fri, 30 Oct 2026 21:06:47 +0900 Subject: [PATCH 3/3] Stabilize 010_index_concurrently_upsert --- .../t/010_index_concurrently_upsert.pl | 55 +++++++++++++------ 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl b/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl index 50a0e7db8f7..bc3fade60fe 100644 --- a/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl +++ b/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl @@ -117,7 +117,7 @@ wakeup_injection_point($node, # Wakeup s2 (exec-insert-before-insert-speculative) wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); # Cleanup test 1 $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -177,7 +177,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -238,7 +238,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -298,7 +298,7 @@ wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -357,7 +357,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -418,7 +418,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -478,7 +478,7 @@ wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -537,7 +537,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -598,7 +598,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -645,7 +645,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-swap'); wakeup_injection_point($node, 'exec-init-partition-after-get-partition-ancestors'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -739,7 +739,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -828,7 +828,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblexpr'); @@ -921,7 +921,7 @@ SELECT injection_points_wakeup('$point_name'); } # Wait for any pending query to complete, capture stderr, and close the session. -# Returns the stderr output (excluding internal markers). +# Returns the stderr output (excluding internal markers) and the backend PID. sub safe_quit { my ($session) = @_; @@ -943,18 +943,41 @@ sub safe_quit my $stderr = $session->{stderr}; $stderr =~ s/$banner_match//; + # The session is idle now, so its backend PID can be queried safely. + $session->{stdout} = ''; + $session->{stderr} = ''; + my $pid = $session->query_safe('SELECT pg_backend_pid()', verbose => 0); + chomp $pid; + # Close the session $session->quit; - return $stderr; + return ($stderr, $pid); } -# Helper function: verify that the given sessions exit cleanly. +# Helper function: verify that the given sessions exit cleanly, then wait for +# their server backends to finish. This ensures that injection points are +# cleaned up by a before_shmem_exit callback. sub clean_safe_quit_ok { + my $node = shift; + my @backend_pids; my $i = 1; foreach my $session (@_) { - is(safe_quit($session), '', "session " . $i++ . " quit cleanly"); + my ($stderr, $pid) = safe_quit($session); + + is($stderr, '', "session " . $i++ . " quit cleanly"); + die "invalid backend PID: $pid" unless $pid =~ /^\d+$/; + push @backend_pids, $pid; } + + # Confirmed all sessions are closed. Ensure all related backends have + # exited. + my $pid_list = join(',', @backend_pids); + + $node->poll_query_until( + 'postgres', + "SELECT count(*) = 0 FROM pg_stat_activity WHERE pid IN ($pid_list)") + or die "timed out waiting for backends $pid_list to exit"; } -- 2.52.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-10-30 21:56  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-10-30 21:56 UTC (permalink / raw)
  To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Hi,

On Fri, Oct 30, 2026 at 5:37 AM Hayato Kuroda (Fujitsu)
<kuroda.hayato@fujitsu.com> wrote:
>
> Hi,
>
> > `check-world` with this sleep reveals also other tests suffering from the
> > same disease:
> > src/test/modules/test_misc/t/010_index_concurrently_upsert.pl
> > repack_toast
> > repack_missingval
> > repack_temporal
> > repack_temporal_multirange
>
> I analyzed other issues and attaches patch set. 0001 fixes the

I've reviewed only the 0001 patch. While I agree with your analysis, I
think it's sufficient to call injection_points_detach() before quit,
no? Also, the following codes in 051_effective_wal_level.pl seems to
have the same issue;

    # Resume the slot synchronization; it must skip persisting the slot.
    $log_offset = -s $standby5->logfile;
    $standby5->safe_psql('postgres',
        qq[select injection_points_wakeup('replication-slot-create-begin')]);
    $standby5->wait_for_log(
        qr/could not synchronize replication slot "sync_slot"/, $log_offset);
    $psql_sync_slot->quit;

A new background psql session begins later and attaches the same
injection point. I think we should add injectoin_points_detach()
before _wakeup().

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-11-02 04:47  Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Hayato Kuroda (Fujitsu) @ 2026-11-02 04:47 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Hi Sawada-san,

> I've reviewed only the 0001 patch. While I agree with your analysis,

Thanks!

> I
> think it's sufficient to call injection_points_detach() before quit,
> no?

That's not enough. As I posted in the previous post, exiting backend which calls
_set_local can cleanup injection points registered by other backends.
Here below scenario can still happen:

0. assuming that there is a background psql session, and the related backend (b1)
   does _set_local() and _attach() for an injection point "logical-decoding-activation".
   b1 has been storing the name in inj_list_local.
1. a backend (b2) calls _detach(). An injection point is removed from the shared hash.
2. the background psql session quits, the b1 starts exiting (and delayed).
3. another backend (b3) calls _set_local() and _attach() for the same injection
   point "logical-decoding-activation". It's registered on the shared hash.
4. b1 reaches the cleanup function and removes "logical-decoding-activation"
   from the shared hash.
5. b3 calls pg_create_logical_replication_slot(). Since the injection point has
   already been removed it won't wait anymore.
6. upcoming wait_for_event() stucks since nobody waits there.

I confirmed that the test could still fail by adding detach() before the quit atop the reproducer.

Alternative fix idea is to ensure the backend process exits, v2 implements the same.
If we want to use _detach() approach we need to fix race condition for injection
ponits side.

> Also, the following codes in 051_effective_wal_level.pl seems to
> have the same issue;

Right, fixed.

[1]: https://www.postgresql.org/message-id/OS7PR01MB183172A425382C8A781DB153FF56D2%40OS7PR01MB18317.jpnpr...

Best regards,
Hayato Kuroda
FUJITSU LIMITED



Attachments: download all (3 files, .tar.gz)

v2-0001-Stabilize-051_effective_wal_level.patch (application/octet-stream, 6.1K) download From 138b5f06d1a55a03561f9fd98971e5b6c3dbf377 Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Mon, 2 Nov 2026 13:43:46 +0900 Subject: [PATCH v2 1/3] Stabilize 051_effective_wal_level --- .../recovery/t/051_effective_wal_level.pl | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 4aa26ec786b..adb7555ae76 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -32,6 +32,19 @@ sub wait_for_logical_decoding_disabled qq[select current_setting('effective_wal_level') = 'replica';]); } +# Close a background psql session and wait for its server backend to finish +# exit processing so that its local injection point names can be safely reused. +sub quit_and_wait_for_backend +{ + my ($node, $background_psql, $backend_pid) = @_; + + die "invalid backend PID: $backend_pid" unless $backend_pid =~ /^\d+$/; + $background_psql->quit; + $node->poll_query_until('postgres', + qq[select count(*) = 0 from pg_stat_activity where pid = $backend_pid]) + or die "timed out waiting for backend $backend_pid to exit"; +} + # Initialize the primary server with wal_level = 'replica'. my $primary = PostgreSQL::Test::Cluster->new('primary'); $primary->init(allows_streaming => 1); @@ -416,6 +429,8 @@ if ( $ENV{enable_injection_points} eq 'yes' # Start a psql session and stop it in the middle of the activation process. my $psql_create_slot = $primary->background_psql('postgres'); + my $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()', verbose => 0); $psql_create_slot->query_until( qr/create_slot_1/, q(\echo create_slot_1 @@ -443,7 +458,8 @@ select pg_create_logical_replication_slot('slot_1', 'test_decoding'); qq[select injection_points_wakeup('logical-decoding-activation')]); # Let the released backend finish creating its slot. - $psql_create_slot->quit; + quit_and_wait_for_backend($primary, $psql_create_slot, + $psql_create_slot_pid); # Decode from slot_2, whose start point precedes where a redundant # status-change record would have been written; this fails in xlog_decode() @@ -470,6 +486,8 @@ select pg_drop_replication_slot('slot_2'); # interrupted. $psql_create_slot = $primary->background_psql('postgres', on_error_stop => 0); + $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()', verbose => 0); # Start the logical decoding activation process upon creating the logical # slot, but it will wait due to the injection point. @@ -497,11 +515,14 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled wait_for_logical_decoding_disabled($primary); pass("the activation process aborted"); - $psql_create_slot->quit; + quit_and_wait_for_backend($primary, $psql_create_slot, + $psql_create_slot_pid); # Test concurrent activation processes run and one is interrupted. $psql_create_slot = $primary->background_psql('postgres', on_error_stop => 0); + $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()', verbose => 0); # Start a psql session and stops in the middle of the activation # process. @@ -540,7 +561,8 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled "effective_wal_level remains 'logical' even after the concurrent activation is interrupted" ); - $psql_create_slot->quit; + quit_and_wait_for_backend($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 @@ -596,6 +618,8 @@ hot_standby_feedback = on # information but before creating the local slot. Note that this point # waits when reaching the creation of slot "sync_slot". my $psql_sync_slot = $standby5->background_psql('postgres'); + my $psql_sync_slot_pid = + $psql_sync_slot->query_safe('select pg_backend_pid()', verbose => 0); $psql_sync_slot->query_until( qr/sync_slots/, q(\echo sync_slots @@ -622,7 +646,8 @@ select pg_sync_replication_slots(); qq[select injection_points_wakeup('replication-slot-create-begin')]); $standby5->wait_for_log( qr/could not synchronize replication slot "sync_slot"/, $log_offset); - $psql_sync_slot->quit; + quit_and_wait_for_backend($standby5, $psql_sync_slot, + $psql_sync_slot_pid); is( $standby5->safe_psql( 'postgres', qq[select count(*) from pg_replication_slots]), '0', @@ -643,6 +668,8 @@ select pg_sync_replication_slots(); ); $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot_pid = + $psql_sync_slot->query_safe('select pg_backend_pid()', verbose => 0); $psql_sync_slot->query_until( qr/sync_slots/, q(\echo sync_slots @@ -696,7 +723,8 @@ select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); select pg_drop_replication_slot('sync_slot'); ]); $primary->wait_for_replay_catchup($standby5); - $psql_sync_slot->quit; + quit_and_wait_for_backend($standby5, $psql_sync_slot, + $psql_sync_slot_pid); # The slot created on retry may or may not have been persisted by the # time the remote slot was dropped. One more synchronization cycle @@ -734,6 +762,8 @@ select pg_drop_replication_slot('sync_slot'); # Start creating a logical slot, stopping it before creating the slot. $psql_create_slot = $standby5->background_psql('postgres', on_error_stop => 0); + $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()', verbose => 0); # Note that this point waits when reaching the creation of slot # "standby5_slot". $psql_create_slot->query_until( @@ -761,7 +791,8 @@ select pg_create_logical_replication_slot('standby5_slot', 'test_decoding'); $standby5->wait_for_log( qr/ERROR: .* logical decoding on standby requires "effective_wal_level" >= "logical" on the primary/, $log_offset); - $psql_create_slot->quit; + quit_and_wait_for_backend($standby5, $psql_create_slot, + $psql_create_slot_pid); is( $standby5->safe_psql( 'postgres', qq[select count(*) from pg_replication_slots]), '0', -- 2.52.0
v2-0002-Ensure-injection-point-repack-concurrently-before.patch (application/octet-stream, 1.3K) download From 34c6ca4cdf197fa53e3565463b52a1949c37095b Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Fri, 30 Oct 2026 20:03:24 +0900 Subject: [PATCH v2 2/3] Ensure injection point repack-concurrently-before-lock is detached --- .../modules/injection_points/expected/repack_dropped.out | 5 +++++ src/test/modules/injection_points/specs/repack_dropped.spec | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/test/modules/injection_points/expected/repack_dropped.out b/src/test/modules/injection_points/expected/repack_dropped.out index 4186ce4981c..44ba55d94a6 100644 --- a/src/test/modules/injection_points/expected/repack_dropped.out +++ b/src/test/modules/injection_points/expected/repack_dropped.out @@ -49,3 +49,8 @@ id|fits_in_one_block 3|t (3 rows) +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack_dropped.spec b/src/test/modules/injection_points/specs/repack_dropped.spec index 8dabd4fafb4..ec888f86bbc 100644 --- a/src/test/modules/injection_points/specs/repack_dropped.spec +++ b/src/test/modules/injection_points/specs/repack_dropped.spec @@ -64,6 +64,11 @@ step s2_noop { } +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + session s3 step s3_updates { -- 2.52.0
v2-0003-Stabilize-010_index_concurrently_upsert.patch (application/octet-stream, 6.1K) download From 6cffe8b5b8a5f12f8b1dcf6805af82a5205bbb97 Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Fri, 30 Oct 2026 21:06:47 +0900 Subject: [PATCH v2 3/3] Stabilize 010_index_concurrently_upsert --- .../t/010_index_concurrently_upsert.pl | 55 +++++++++++++------ 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl b/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl index 50a0e7db8f7..bc3fade60fe 100644 --- a/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl +++ b/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl @@ -117,7 +117,7 @@ wakeup_injection_point($node, # Wakeup s2 (exec-insert-before-insert-speculative) wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); # Cleanup test 1 $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -177,7 +177,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -238,7 +238,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -298,7 +298,7 @@ wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -357,7 +357,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -418,7 +418,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -478,7 +478,7 @@ wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -537,7 +537,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -598,7 +598,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -645,7 +645,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-swap'); wakeup_injection_point($node, 'exec-init-partition-after-get-partition-ancestors'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -739,7 +739,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -828,7 +828,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblexpr'); @@ -921,7 +921,7 @@ SELECT injection_points_wakeup('$point_name'); } # Wait for any pending query to complete, capture stderr, and close the session. -# Returns the stderr output (excluding internal markers). +# Returns the stderr output (excluding internal markers) and the backend PID. sub safe_quit { my ($session) = @_; @@ -943,18 +943,41 @@ sub safe_quit my $stderr = $session->{stderr}; $stderr =~ s/$banner_match//; + # The session is idle now, so its backend PID can be queried safely. + $session->{stdout} = ''; + $session->{stderr} = ''; + my $pid = $session->query_safe('SELECT pg_backend_pid()', verbose => 0); + chomp $pid; + # Close the session $session->quit; - return $stderr; + return ($stderr, $pid); } -# Helper function: verify that the given sessions exit cleanly. +# Helper function: verify that the given sessions exit cleanly, then wait for +# their server backends to finish. This ensures that injection points are +# cleaned up by a before_shmem_exit callback. sub clean_safe_quit_ok { + my $node = shift; + my @backend_pids; my $i = 1; foreach my $session (@_) { - is(safe_quit($session), '', "session " . $i++ . " quit cleanly"); + my ($stderr, $pid) = safe_quit($session); + + is($stderr, '', "session " . $i++ . " quit cleanly"); + die "invalid backend PID: $pid" unless $pid =~ /^\d+$/; + push @backend_pids, $pid; } + + # Confirmed all sessions are closed. Ensure all related backends have + # exited. + my $pid_list = join(',', @backend_pids); + + $node->poll_query_until( + 'postgres', + "SELECT count(*) = 0 FROM pg_stat_activity WHERE pid IN ($pid_list)") + or die "timed out waiting for backends $pid_list to exit"; } -- 2.52.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-11-02 19:44  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-11-02 19:44 UTC (permalink / raw)
  To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Sun, Nov 1, 2026 at 8:47 PM Hayato Kuroda (Fujitsu)
<kuroda.hayato@fujitsu.com> wrote:
>
> Hi Sawada-san,
>
> > I've reviewed only the 0001 patch. While I agree with your analysis,
>
> Thanks!
>
> > I
> > think it's sufficient to call injection_points_detach() before quit,
> > no?
>
> That's not enough. As I posted in the previous post, exiting backend which calls
> _set_local can cleanup injection points registered by other backends.
> Here below scenario can still happen:
>
> 0. assuming that there is a background psql session, and the related backend (b1)
>    does _set_local() and _attach() for an injection point "logical-decoding-activation".
>    b1 has been storing the name in inj_list_local.
> 1. a backend (b2) calls _detach(). An injection point is removed from the shared hash.
> 2. the background psql session quits, the b1 starts exiting (and delayed).
> 3. another backend (b3) calls _set_local() and _attach() for the same injection
>    point "logical-decoding-activation". It's registered on the shared hash.
> 4. b1 reaches the cleanup function and removes "logical-decoding-activation"
>    from the shared hash.
> 5. b3 calls pg_create_logical_replication_slot(). Since the injection point has
>    already been removed it won't wait anymore.
> 6. upcoming wait_for_event() stucks since nobody waits there
>
> I confirmed that the test could still fail by adding detach() before the quit atop the reproducer.

Agreed.

> Alternative fix idea is to ensure the backend process exits, v2 implements the same.
> If we want to use _detach() approach we need to fix race condition for injection
> ponits side.
>
> > Also, the following codes in 051_effective_wal_level.pl seems to
> > have the same issue;
>
> Right, fixed.

The 0001 patch basically looks good to me. Is there any reason that
the patch sets "verbose => 0" to some query_safe() calls? Also, I'd
suggest renaming the support function to quit_and_wait().

The 0002 patch looks good to me.

I'll review the 0003 patch soon.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-11-03 04:20  Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Hayato Kuroda (Fujitsu) @ 2026-11-03 04:20 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Hi Sawada-san,

> The 0001 patch basically looks good to me. Is there any reason that
> the patch sets "verbose => 0" to some query_safe() calls? Also, I'd
> suggest renaming the support function to quit_and_wait().

I just tried to suppress output, not mandatory. PSA fixed version.
I fixed 0001 as well.

> I'll review the 0003 patch soon.

Thanks!

Best regards,
Hayato Kuroda
FUJITSU LIMITED 



Attachments: download all (3 files, .tar.gz)

v3-0001-Stabilize-051_effective_wal_level.patch (application/octet-stream, 6.0K) download From 01b0299c7c31d6d8992a1505c34dad061f425427 Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Mon, 2 Nov 2026 13:43:46 +0900 Subject: [PATCH v3 1/3] Stabilize 051_effective_wal_level --- .../recovery/t/051_effective_wal_level.pl | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/src/test/recovery/t/051_effective_wal_level.pl b/src/test/recovery/t/051_effective_wal_level.pl index 4aa26ec786b..b6dbedc1117 100644 --- a/src/test/recovery/t/051_effective_wal_level.pl +++ b/src/test/recovery/t/051_effective_wal_level.pl @@ -32,6 +32,19 @@ sub wait_for_logical_decoding_disabled qq[select current_setting('effective_wal_level') = 'replica';]); } +# Close a background psql session and wait for its server backend to finish +# exit processing so that its local injection point names can be safely reused. +sub quit_and_wait +{ + my ($node, $background_psql, $backend_pid) = @_; + + die "invalid backend PID: $backend_pid" unless $backend_pid =~ /^\d+$/; + $background_psql->quit; + $node->poll_query_until('postgres', + qq[select count(*) = 0 from pg_stat_activity where pid = $backend_pid]) + or die "timed out waiting for backend $backend_pid to exit"; +} + # Initialize the primary server with wal_level = 'replica'. my $primary = PostgreSQL::Test::Cluster->new('primary'); $primary->init(allows_streaming => 1); @@ -416,6 +429,8 @@ if ( $ENV{enable_injection_points} eq 'yes' # Start a psql session and stop it in the middle of the activation process. my $psql_create_slot = $primary->background_psql('postgres'); + my $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()'); $psql_create_slot->query_until( qr/create_slot_1/, q(\echo create_slot_1 @@ -443,7 +458,8 @@ select pg_create_logical_replication_slot('slot_1', 'test_decoding'); qq[select injection_points_wakeup('logical-decoding-activation')]); # Let the released backend finish creating its slot. - $psql_create_slot->quit; + quit_and_wait($primary, $psql_create_slot, + $psql_create_slot_pid); # Decode from slot_2, whose start point precedes where a redundant # status-change record would have been written; this fails in xlog_decode() @@ -470,6 +486,8 @@ select pg_drop_replication_slot('slot_2'); # interrupted. $psql_create_slot = $primary->background_psql('postgres', on_error_stop => 0); + $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()'); # Start the logical decoding activation process upon creating the logical # slot, but it will wait due to the injection point. @@ -497,11 +515,14 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled wait_for_logical_decoding_disabled($primary); pass("the activation process aborted"); - $psql_create_slot->quit; + quit_and_wait($primary, $psql_create_slot, + $psql_create_slot_pid); # Test concurrent activation processes run and one is interrupted. $psql_create_slot = $primary->background_psql('postgres', on_error_stop => 0); + $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()'); # Start a psql session and stops in the middle of the activation # process. @@ -540,7 +561,8 @@ select pg_cancel_backend(pid) from pg_stat_activity where query ~ 'slot_canceled "effective_wal_level remains 'logical' even after the concurrent activation is interrupted" ); - $psql_create_slot->quit; + 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 @@ -596,6 +618,8 @@ hot_standby_feedback = on # information but before creating the local slot. Note that this point # waits when reaching the creation of slot "sync_slot". my $psql_sync_slot = $standby5->background_psql('postgres'); + my $psql_sync_slot_pid = + $psql_sync_slot->query_safe('select pg_backend_pid()'); $psql_sync_slot->query_until( qr/sync_slots/, q(\echo sync_slots @@ -622,7 +646,8 @@ select pg_sync_replication_slots(); qq[select injection_points_wakeup('replication-slot-create-begin')]); $standby5->wait_for_log( qr/could not synchronize replication slot "sync_slot"/, $log_offset); - $psql_sync_slot->quit; + quit_and_wait($standby5, $psql_sync_slot, + $psql_sync_slot_pid); is( $standby5->safe_psql( 'postgres', qq[select count(*) from pg_replication_slots]), '0', @@ -643,6 +668,8 @@ select pg_sync_replication_slots(); ); $psql_sync_slot = $standby5->background_psql('postgres'); + $psql_sync_slot_pid = + $psql_sync_slot->query_safe('select pg_backend_pid()'); $psql_sync_slot->query_until( qr/sync_slots/, q(\echo sync_slots @@ -696,7 +723,8 @@ select pg_create_logical_replication_slot('test_slot4', 'test_decoding'); select pg_drop_replication_slot('sync_slot'); ]); $primary->wait_for_replay_catchup($standby5); - $psql_sync_slot->quit; + quit_and_wait($standby5, $psql_sync_slot, + $psql_sync_slot_pid); # The slot created on retry may or may not have been persisted by the # time the remote slot was dropped. One more synchronization cycle @@ -734,6 +762,8 @@ select pg_drop_replication_slot('sync_slot'); # Start creating a logical slot, stopping it before creating the slot. $psql_create_slot = $standby5->background_psql('postgres', on_error_stop => 0); + $psql_create_slot_pid = + $psql_create_slot->query_safe('select pg_backend_pid()'); # Note that this point waits when reaching the creation of slot # "standby5_slot". $psql_create_slot->query_until( @@ -761,7 +791,8 @@ select pg_create_logical_replication_slot('standby5_slot', 'test_decoding'); $standby5->wait_for_log( qr/ERROR: .* logical decoding on standby requires "effective_wal_level" >= "logical" on the primary/, $log_offset); - $psql_create_slot->quit; + quit_and_wait($standby5, $psql_create_slot, + $psql_create_slot_pid); is( $standby5->safe_psql( 'postgres', qq[select count(*) from pg_replication_slots]), '0', -- 2.52.0
v3-0002-Ensure-injection-point-repack-concurrently-before.patch (application/octet-stream, 1.3K) download From 8df9cc908be925996ec6953a680370524dbe4625 Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Fri, 30 Oct 2026 20:03:24 +0900 Subject: [PATCH v3 2/3] Ensure injection point repack-concurrently-before-lock is detached --- .../modules/injection_points/expected/repack_dropped.out | 5 +++++ src/test/modules/injection_points/specs/repack_dropped.spec | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/test/modules/injection_points/expected/repack_dropped.out b/src/test/modules/injection_points/expected/repack_dropped.out index 4186ce4981c..44ba55d94a6 100644 --- a/src/test/modules/injection_points/expected/repack_dropped.out +++ b/src/test/modules/injection_points/expected/repack_dropped.out @@ -49,3 +49,8 @@ id|fits_in_one_block 3|t (3 rows) +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/specs/repack_dropped.spec b/src/test/modules/injection_points/specs/repack_dropped.spec index 8dabd4fafb4..ec888f86bbc 100644 --- a/src/test/modules/injection_points/specs/repack_dropped.spec +++ b/src/test/modules/injection_points/specs/repack_dropped.spec @@ -64,6 +64,11 @@ step s2_noop { } +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + session s3 step s3_updates { -- 2.52.0
v3-0003-Stabilize-010_index_concurrently_upsert.patch (application/octet-stream, 6.1K) download From 65d0a826ac2ce38f41339640b0684ab478851e38 Mon Sep 17 00:00:00 2001 From: Hayato Kuroda <kuroda.hayato@fujitsu.com> Date: Fri, 30 Oct 2026 21:06:47 +0900 Subject: [PATCH v3 3/3] Stabilize 010_index_concurrently_upsert --- .../t/010_index_concurrently_upsert.pl | 55 +++++++++++++------ 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl b/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl index 50a0e7db8f7..80e5cfaa5fd 100644 --- a/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl +++ b/src/test/modules/test_misc/t/010_index_concurrently_upsert.pl @@ -117,7 +117,7 @@ wakeup_injection_point($node, # Wakeup s2 (exec-insert-before-insert-speculative) wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); # Cleanup test 1 $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -177,7 +177,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -238,7 +238,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -298,7 +298,7 @@ wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -357,7 +357,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -418,7 +418,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblpk'); @@ -478,7 +478,7 @@ wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -537,7 +537,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -598,7 +598,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-set-dead'); wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -645,7 +645,7 @@ wakeup_injection_point($node, 'reindex-relation-concurrently-before-swap'); wakeup_injection_point($node, 'exec-init-partition-after-get-partition-ancestors'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -739,7 +739,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblparted'); @@ -828,7 +828,7 @@ wakeup_injection_point($node, 'exec-insert-before-insert-speculative'); wakeup_injection_point($node, 'check-exclusion-or-unique-constraint-no-conflict'); -clean_safe_quit_ok($s1, $s2, $s3); +clean_safe_quit_ok($node, $s1, $s2, $s3); $node->safe_psql('postgres', 'TRUNCATE TABLE test.tblexpr'); @@ -921,7 +921,7 @@ SELECT injection_points_wakeup('$point_name'); } # Wait for any pending query to complete, capture stderr, and close the session. -# Returns the stderr output (excluding internal markers). +# Returns the stderr output (excluding internal markers) and the backend PID. sub safe_quit { my ($session) = @_; @@ -943,18 +943,41 @@ sub safe_quit my $stderr = $session->{stderr}; $stderr =~ s/$banner_match//; + # The session is idle now, so its backend PID can be queried safely. + $session->{stdout} = ''; + $session->{stderr} = ''; + my $pid = $session->query_safe('SELECT pg_backend_pid()'); + chomp $pid; + # Close the session $session->quit; - return $stderr; + return ($stderr, $pid); } -# Helper function: verify that the given sessions exit cleanly. +# Helper function: verify that the given sessions exit cleanly, then wait for +# their server backends to finish. This ensures that injection points are +# cleaned up by a before_shmem_exit callback. sub clean_safe_quit_ok { + my $node = shift; + my @backend_pids; my $i = 1; foreach my $session (@_) { - is(safe_quit($session), '', "session " . $i++ . " quit cleanly"); + my ($stderr, $pid) = safe_quit($session); + + is($stderr, '', "session " . $i++ . " quit cleanly"); + die "invalid backend PID: $pid" unless $pid =~ /^\d+$/; + push @backend_pids, $pid; } + + # Confirmed all sessions are closed. Ensure all related backends have + # exited. + my $pid_list = join(',', @backend_pids); + + $node->poll_query_until( + 'postgres', + "SELECT count(*) = 0 FROM pg_stat_activity WHERE pid IN ($pid_list)") + or die "timed out waiting for backends $pid_list to exit"; } -- 2.52.0
^ permalink raw reply [nested|flat] 59+ messages in thread

* Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-11-06 18:24  Masahiko Sawada <sawada.mshk@gmail.com>
  parent: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  0 siblings, 1 reply; 59+ messages in thread

From: Masahiko Sawada @ 2026-11-06 18:24 UTC (permalink / raw)
  To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

On Mon, Nov 2, 2026 at 8:20 PM Hayato Kuroda (Fujitsu)
<kuroda.hayato@fujitsu.com> wrote:
>
> Hi Sawada-san,
>
> > The 0001 patch basically looks good to me. Is there any reason that
> > the patch sets "verbose => 0" to some query_safe() calls? Also, I'd
> > suggest renaming the support function to quit_and_wait().
>
> I just tried to suppress output, not mandatory. PSA fixed version.
> I fixed 0001 as well.

Thank you for updating the patch! I pushed 0001 and 0002.

> > I'll review the 0003 patch soon.

IIUC the problem that the 0003 patch tries to fix is somewhat
different from the problem that the 0001 patch fixed. The former is
that a backend's exit cleanup can detach an injection point that is
attached by another backend, whereas the latter is that attaching an
injection point can fail with "already defined" error if the backend
behind a background psql session is slow to exit for some reason.

Regarding the former issue, I think it's okay that an injection point
is detached by someone other than the one who attached it, since
injection_points_detach() takes the name of the point and injection
point names are global across backends. The problem is that injection
points are also detached at process exit cleanup time, and it could
detach the point even if it was attached by someone else. So if
another backend attaches the same injection point in between, the
exiting process blindly detaches it even though it didn't attach that
point. In tests with injection points, it's conventional to do
injection_points_detach() and injection_points_wakeup(), and continue
the next test. I think it would not be great for us to have to take
care of this race condition every time we write a test. I guess it
would be better to fix the injection point side so that detaching
points during process exit cleanup affects only the points attached by
itself.

I think it's already a separate topic from the issue reported in this
thread, so I'd suggest starting a new thread for this problem. We can
decide whether we need the 0003 patch based on the discussion there.
Fortunately, the problem in 010_index_concurrently_upsert.pl hasn't
happened on buildfarm yet, so we would have some time to discuss the
right approach for this issue.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com






^ permalink  raw  reply  [nested|flat] 59+ messages in thread

* RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
@ 2026-11-11 01:53  Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
  parent: Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 0 replies; 59+ messages in thread

From: Hayato Kuroda (Fujitsu) @ 2026-11-11 01:53 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-hackers

Hi Sawada-san,

> Thank you for updating the patch! I pushed 0001 and 0002.

Great, thanks!

> IIUC the problem that the 0003 patch tries to fix is somewhat
> different from the problem that the 0001 patch fixed. The former is
> that a backend's exit cleanup can detach an injection point that is
> attached by another backend, whereas the latter is that attaching an
> injection point can fail with "already defined" error if the backend
> behind a background psql session is slow to exit for some reason.

Exactly.

> Regarding the former issue, I think it's okay that an injection point
> is detached by someone other than the one who attached it, since
> injection_points_detach() takes the name of the point and injection
> point names are global across backends.

Right, otherwise, how can the stopped process resume working?

> I guess it
> would be better to fix the injection point side so that detaching
> points during process exit cleanup affects only the points attached by
> itself.

I also mentioned the possibility in [1] but I have not tried yet. +1 it's the
proper approach.

> I think it's already a separate topic from the issue reported in this
> thread, so I'd suggest starting a new thread for this problem.

Sure, I would fork a new thread after implementing both approaches.
Will include you and Alexander in CC. Let’s close this thread.


[1]: https://www.postgresql.org/message-id/OS7PR01MB183172A425382C8A781DB153FF56D2%40OS7PR01MB18317.jpnpr...

Best regards,
Hayato Kuroda
FUJITSU LIMITED




^ permalink  raw  reply  [nested|flat] 59+ messages in thread


end of thread, other threads:[~2026-11-11 01:53 UTC | newest]

Thread overview: 59+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-07-10 04:18 Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation Srinath Reddy Sadipiralla <srinath2133@gmail.com>
2026-07-10 04:22 ` Srinath Reddy Sadipiralla <srinath2133@gmail.com>
2026-07-14 21:02   ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-16 01:21     ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-20 16:47       ` Srinath Reddy Sadipiralla <srinath2133@gmail.com>
2026-07-21 00:42         ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-21 04:52           ` Srinath Reddy Sadipiralla <srinath2133@gmail.com>
2026-07-22 13:38       ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-24 07:20         ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-27 16:05           ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-29 05:28             ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-23 11:43       ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-27 16:39         ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-29 10:21           ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-30 07:06             ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-30 09:00               ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-30 20:58                 ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-30 21:48                   ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-31 00:52                     ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-31 03:49                       ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-31 04:00                         ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-01 05:42                           ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-10-30 08:00                         ` Alexander Lakhin <exclusion@gmail.com>
2026-10-30 10:33                           ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-10-30 12:37                             ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-10-30 21:56                               ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-11-02 04:47                                 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-02 19:44                                   ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-11-03 04:20                                     ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-06 18:24                                       ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-11-11 01:53                                         ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-09-22 06:32       ` Nikolay Samokhvalov <nik@postgres.ai>
2026-09-22 20:15         ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-09-24 09:19           ` shveta malik <shveta.malik@gmail.com>
2026-09-24 20:29             ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-09-24 11:40           ` Nisha Moond <nisha.moond412@gmail.com>
2026-09-24 22:08             ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-09-25 08:02               ` Nisha Moond <nisha.moond412@gmail.com>
2026-09-25 09:28               ` shveta malik <shveta.malik@gmail.com>
2026-09-25 22:24                 ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-09-26 21:44                   ` Amit Kapila <amit.kapila16@gmail.com>
2026-09-28 19:48                     ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-09-29 00:35                       ` Amit Kapila <amit.kapila16@gmail.com>
2026-09-28 05:00                   ` shveta malik <shveta.malik@gmail.com>
2026-09-28 05:03                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-10-01 11:08                   ` Nisha Moond <nisha.moond412@gmail.com>
2026-10-05 22:26                     ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-10-06 03:24                       ` shveta malik <shveta.malik@gmail.com>
2026-10-06 05:46                         ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-10-07 02:52                           ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-10-07 03:43                           ` shveta malik <shveta.malik@gmail.com>
2026-10-07 19:07                             ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-10-08 00:33                               ` Fujii Masao <masao.fujii@gmail.com>
2026-10-08 01:09                                 ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-10-08 03:25                                   ` shveta malik <shveta.malik@gmail.com>
2026-10-08 18:27                                     ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-09-25 13:21               ` Zhijie Hou <houzhijie22@gmail.com>
2026-09-25 22:23                 ` Masahiko Sawada <sawada.mshk@gmail.com>
2026-07-16 05:06     ` Srinath Reddy Sadipiralla <srinath2133@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox