Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
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.
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
Fwd: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
---------- 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>
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.
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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Thu, Jul 9, 2026 at 9:23 PM Srinath Reddy Sadipiralla
wrote:
>
>
>
> ---------- Forwarded message ---------
> From: Srinath Reddy Sadipiralla
> 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
> Cc: Masahiko Sawada
>
>
> 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Дата:
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.
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Дата:
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."
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/
"The truth is... I am Iron Man."
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Jul 20, 2026 at 9:47 AM Srinath Reddy Sadipiralla
wrote:
>
> Hi Masahiko-san,
>
> On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Дата:
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. "
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/
" Maybe that's what Batman is about. Not winning. But failing, and getting back up. "
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada wrote:
>
> On Tue, Jul 14, 2026 at 2:02 PM Masahiko Sawada 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.
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Masahiko Sawada writes: > On Thu, Jul 30, 2026 at 5:52 PM Tom Lane 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov wrote:
>
> On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Sep 23, 2026 at 1:46 AM Masahiko Sawada wrote:
>
> On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov wrote:
> >
> > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> > 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Wed, Sep 23, 2026 at 1:45 AM Masahiko Sawada wrote: > > On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov wrote: > > > > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada > > 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Thu, Sep 24, 2026 at 2:19 AM shveta malik wrote:
>
> On Wed, Sep 23, 2026 at 1:46 AM Masahiko Sawada wrote:
> >
> > On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov wrote:
> > >
> > > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada
> > > 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond wrote: > > On Wed, Sep 23, 2026 at 1:45 AM Masahiko Sawada wrote: > > > > On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov wrote: > > > > > > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada > > > 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada wrote: > > On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond wrote: > > > > On Wed, Sep 23, 2026 at 1:45 AM Masahiko Sawada wrote: > > > > > > On Mon, Sep 21, 2026 at 11:32 PM Nikolay Samokhvalov wrote: > > > > > > > > On Thu, Jul 16, 2026 at 6:52 AM Masahiko Sawada > > > > 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Hi, On Fri, Sep 25, 2026 at 6:09 AM Masahiko Sawada wrote: > > On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Fri, Sep 25, 2026 at 6:21 AM Zhijie Hou wrote: > > Hi, > > On Fri, Sep 25, 2026 at 6:09 AM Masahiko Sawada wrote: > > > > On Thu, Sep 24, 2026 at 4:41 AM Nisha Moond 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Fri, Sep 25, 2026 at 2:28 AM shveta malik wrote: > > On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Fri, Sep 25, 2026 at 6:25 PM Masahiko Sawada 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.
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada wrote: > > On Fri, Sep 25, 2026 at 2:28 AM shveta malik wrote: > > > > On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada wrote: > > On Fri, Sep 25, 2026 at 2:28 AM shveta malik wrote: > > > > On Fri, Sep 25, 2026 at 3:39 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Sat, Sep 26, 2026 at 2:44 PM Amit Kapila wrote:
>
> On Fri, Sep 25, 2026 at 6:25 PM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Mon, Sep 28, 2026 at 3:49 PM Masahiko Sawada wrote: > > On Sat, Sep 26, 2026 at 2:44 PM Amit Kapila 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.
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada 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:
--- 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond wrote: > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada wrote: > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond wrote: > > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Mon, Oct 5, 2026 at 8:24 PM shveta malik wrote: > > On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada wrote: > > > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond wrote: > > > > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Oct 5, 2026 at 10:46 PM Masahiko Sawada wrote: > > On Mon, Oct 5, 2026 at 8:24 PM shveta malik wrote: > > > > On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada wrote: > > > > > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond wrote: > > > > > > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Oct 6, 2026 at 11:16 AM Masahiko Sawada wrote: > > On Mon, Oct 5, 2026 at 8:24 PM shveta malik wrote: > > > > On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada wrote: > > > > > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond wrote: > > > > > > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Oct 6, 2026 at 8:43 PM shveta malik wrote: > > On Tue, Oct 6, 2026 at 11:16 AM Masahiko Sawada wrote: > > > > On Mon, Oct 5, 2026 at 8:24 PM shveta malik wrote: > > > > > > On Tue, Oct 6, 2026 at 3:57 AM Masahiko Sawada wrote: > > > > > > > > On Thu, Oct 1, 2026 at 4:08 AM Nisha Moond wrote: > > > > > > > > > > On Sat, Sep 26, 2026 at 3:54 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
On Wed, Oct 7, 2026 at 5:33 PM Fujii Masao wrote:
>
> On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Thu, Oct 8, 2026 at 6:39 AM Masahiko Sawada wrote:
>
> On Wed, Oct 7, 2026 at 5:33 PM Fujii Masao wrote:
> >
> > On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Wed, Oct 7, 2026 at 8:26 PM shveta malik wrote:
>
> On Thu, Oct 8, 2026 at 6:39 AM Masahiko Sawada wrote:
> >
> > On Wed, Oct 7, 2026 at 5:33 PM Fujii Masao wrote:
> > >
> > > On Thu, Oct 8, 2026 at 4:08 AM Masahiko Sawada 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello Sawada-san,
31.07.2026 06:49, Masahiko Sawada wrote:
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
RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
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
RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
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:
```
--- /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]
```
--- 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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Hi,
On Fri, Oct 30, 2026 at 5:37 AM Hayato Kuroda (Fujitsu)
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
RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
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.jpnprd01.prod.outlook.com Best regards, Hayato Kuroda FUJITSU LIMITED
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Sun, Nov 1, 2026 at 8:47 PM Hayato Kuroda (Fujitsu) 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
RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
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
Re: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Nov 2, 2026 at 8:20 PM Hayato Kuroda (Fujitsu) 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
RE: Fix "unexpected logical decoding status change" error; from concurrent logical decoding activation
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
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.jpnprd01.prod.outlook.com Best regards, Hayato Kuroda FUJITSU LIMITED