Hi,

On Mon, Nov16, 2026 at 02:35 PM Masahiko Sawada wrote:
On Sun, Nov 15, 2026 at 8:35 PM Amit Kapila <[email protected]> wrote:
>
> On Mon, Nov 16, 2026 at 9:50 AM Zhijie Hou <[email protected]> wrote:
> >
> > On Sat, Nov14, 2026 at 02:18 PM Masahiko Sawada wrote:
> > > On Fri, Nov 13, 2026 at 7:35 PM Amit Kapila <[email protected]> 
wrote:
> > >
> > > While I agree that retaining the previous reason doesn't make us
> > > persist the slot, I think it's safe only because the previous
> > > reason is never SS_SKIP_NONE for a temporary slot at that point.
> > > That's true today, but it depends on several things and it would
> > > be hard to modify these code correctly in the future.
> > >
> > > I think the root cause is that commit 788ec96d591 replaced
> > > found_consistent_snapshot with the check of
> > > slotsync_skip_reason, but they're not equivalent:
> > > found_consistent_snapshot is false unless the current cycle
> > > synced the slot and found a consistent snapshot, whereas
> > > slotsync_skip_reason is SS_SKIP_NONE unless the current cycle
> > > detected a reason to skip. So an alternative idea would be to
> > > bring back found_consistent_snapshot part from the commit. That
> > > way, the decision of persisting the slot doesn't depend on the
> > > skip_reasons at all.
> > >
> > > As for the reported reason, a temporary slot is the one we have
> > > not confirmed to reach a consistent point yet. So I think we can
> > > simply report no_consistent_snapshot for a temporary slot if the
> > > current cycle didn't find a consistent snapshot, without relying
> > > on what happened in the previous cycles.
> >
> > I think it would be unnecessary to reintroduce the
> > found_consistent_snapshot out-parameter. Because by definition,
> > slotsync_skip_reason is SS_SKIP_NONE (NULL in
> > pg_replication_slots) only when slot synchronization succeeds.
> > Even before commit 788ec96d591 (since commit e68b6adad9),
> > resetting slotsync_skip_reason to SS_SKIP_NONE on a no-op cycle
> > for a temporary slot was already a bug, because synchronization of
> > that temporary slot had not succeeded yet.
> >
>
> I agree that the bug is because we didn't maintain/update
> slotsync_skip_reason correctly and we anyway need to maintain that
> state to correctly display it in pg_replication_slots. Also, the
> slot already carries the information about consistent_snapshot.
> SS_SKIP_NO_CONSISTENT_SNAPSHOT says the slot hasn't reached a
> consistent point, and it is visible in pg_replication_slots. A flag
> passed back to the caller to say the same thing would be a duplicate
> of that state.

I agree that the v2 patch fixes the problem correctly. My concern is
rather about readability and maintainability, which is why I proposed
the PoC patch.

+ else if (slot->data.persistency == RS_TEMPORARY)
+ {
+ /*
+ * We reach this point when a previous cycle updated confirmed_flush
+ * but failed to build a consistent snapshot, and the remote slot has
+ * not advanced beyond the local slot since then.
+ */
+ skip_reason = SS_SKIP_NO_CONSISTENT_SNAPSHOT;
+ }

Some my concerns are:

- When a temporary slot finds a consistent snapshot, it should be
persisted before update_local_synced_slot() is called for the slot
next time. If update_local_synced_slot() is called twice for a
temporary slot without the remote slot advancing, the two calls give
different results. The first call syncs the slot, finds a consistent
snapshot and leaves SS_SKIP_NONE, but the second call enters the new
branch and sets SS_SKIP_NO_CONSISTENT_SNAPSHOT, although nothing has
changed since the first call. This doesn't happen today only because
the caller persists the slot right after the first call.

To make this invariant explicit and catch any future caller changes, I think we can add an assertion at the entry of update_local_synced_slot() verifying that a temporary slot with a valid confirmed_flush always has slotsync_skip_reason != SS_SKIP_NONE. (See the updated patch for details.)

I still prefer this over reintroducing an out-function parameter, since update_local_synced_slot() already has to maintain slotsync_skip_reason accurately on every path for pg_replication_slots. Relying on slot->slotsync_skip_reason != SS_SKIP_NONE in update_and_persist_local_synced_slot() avoids maintaining and passing a duplicate state for the same condition which I think that's worth keeping.

- The comment explains the branch by what happened in a previous
cycle. So one needs to go through the possible history of the slot to
see why it's correct, whereas what the code checks is just that the
temporary slot hasn't found a consistent snapshot in this call.

- We set SS_SKIP_NO_CONSISTENT_SNAPSHOT in two places for what is
actually the same condition, which makes the code harder to follow.

To address these points, I moved found_consistent_snapshot to the outer scope of update_local_synced_slot() and checking "if (slot->data.persistency == RS_TEMPORARY && !found_consistent_snapshot)" in one central place, with the comment updated to explain the check in terms of the current call. This also emits the LOG message in both cases, addressing Amit's point upthread.


I'm concerned that not only changes to this function but also changes
to its callers could break these assumptions, and nothing near those
places would tell us about them.

Attached is the v3 patch set (with the TAP test split into 0002). Please let me know what you think.


--
Best Regards,
Zhijie Hou
From 9a394e9c054185d92a19d90678e3eb6f9087df52 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Mon, 16 Nov 2026 15:43:47 +0800
Subject: [PATCH v3 1/2] Fix premature persistence of synced slots without a
 consistent snapshot.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

During slot synchronization, update_local_synced_slot() attempts to
advance the local slot only when the remote slot's LSN or catalog_xmin
is ahead of the local slot. If the standby cannot build a consistent
snapshot from the slot's restart_lsn, the skip reason is set to
SS_SKIP_NO_CONSISTENT_SNAPSHOT so that
update_and_persist_local_synced_slot() keeps the slot temporary.
However, LogicalSlotAdvanceAndCheckSnapState() has already updated the
local slot's confirmed_flush to the remote slot's value in that cycle.

In a subsequent synchronization cycle, if the remote slot has not
advanced beyond the local slot, update_local_synced_slot() skips the
advance check and resets the skip reason to SS_SKIP_NONE. Following
commit 788ec96d591, update_and_persist_local_synced_slot() relies on
slotsync_skip_reason to decide whether to persist the slot, causing it
to prematurely persist the slot and mark it sync-ready before a
consistent snapshot is built. Using such a slot after promotion can skip
transactions committed before the consistent point, leading to data
loss, or trigger an assertion failure in subsequent sync cycles.

Fix this by tracking whether the current cycle reached a consistent
snapshot across update_local_synced_slot() and setting
SS_SKIP_NO_CONSISTENT_SNAPSHOT whenever a temporary slot has not reached
one.

Reported-by: Masahiko Sawada <[email protected]>
Author: Zhijie Hou <[email protected]>
Reviewed-by: Masahiko Sawada <[email protected]>
Reviewed-by: Bertrand Drouvot <[email protected]>
Reviewed-by: João Rito <[email protected]>
Reviewed-by: Amit Kapila <[email protected]>
Discussion: 
https://postgr.es/m/cad21aoddn9qj2q5dnkw9daazvoh-9yef7jw64qphjgqi3yj...@mail.gmail.com
Backpatch-through: 19
---
 src/backend/replication/logical/slotsync.c | 51 ++++++++++++++--------
 1 file changed, 34 insertions(+), 17 deletions(-)

diff --git a/src/backend/replication/logical/slotsync.c 
b/src/backend/replication/logical/slotsync.c
index 7bd14bb2e74..0441eaf4141 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -224,11 +224,21 @@ update_local_synced_slot(RemoteSlot *remote_slot, Oid 
remote_dbid)
        ReplicationSlot *slot = MyReplicationSlot;
        bool            updated_xmin_or_lsn = false;
        bool            updated_config = false;
+       bool            found_consistent_snapshot = false;
        SlotSyncSkipReason skip_reason = SS_SKIP_NONE;
        XLogRecPtr      latestFlushPtr = GetStandbyFlushRecPtr(NULL);
 
        Assert(slot->data.invalidated == RS_INVAL_NONE);
 
+       /*
+        * A temporary slot is either newly created (confirmed_flush is invalid)
+        * or was skipped in its previous sync attempt; if synchronization had
+        * succeeded, the caller would have persisted the slot immediately.
+        */
+       Assert(slot->data.persistency != RS_TEMPORARY ||
+                  !XLogRecPtrIsValid(slot->data.confirmed_flush) ||
+                  slot->slotsync_skip_reason != SS_SKIP_NONE);
+
        /*
         * Make sure that concerned WAL is received and flushed before syncing
         * slot to target lsn received from the primary server.
@@ -335,10 +345,10 @@ update_local_synced_slot(RemoteSlot *remote_slot, Oid 
remote_dbid)
                        SpinLockRelease(&slot->mutex);
 
                        updated_xmin_or_lsn = true;
+                       found_consistent_snapshot = true;
                }
                else
                {
-                       bool            found_consistent_snapshot;
                        XLogRecPtr      old_confirmed_lsn = 
slot->data.confirmed_flush;
                        XLogRecPtr      old_restart_lsn = 
slot->data.restart_lsn;
                        TransactionId old_catalog_xmin = 
slot->data.catalog_xmin;
@@ -355,22 +365,9 @@ update_local_synced_slot(RemoteSlot *remote_slot, Oid 
remote_dbid)
                                                                                
   LSN_FORMAT_ARGS(remote_slot->confirmed_lsn),
                                                                                
   LSN_FORMAT_ARGS(slot->data.confirmed_flush)));
 
-                       /*
-                        * If we can't reach a consistent snapshot, the slot 
won't be
-                        * persisted. See 
update_and_persist_local_synced_slot().
-                        */
-                       if (!found_consistent_snapshot)
-                       {
-                               Assert(MyReplicationSlot->data.persistency == 
RS_TEMPORARY);
-
-                               ereport(LOG,
-                                               errmsg("could not synchronize 
replication slot \"%s\"",
-                                                          remote_slot->name),
-                                               errdetail("Synchronization 
could lead to data loss, because the standby could not build a consistent 
snapshot to decode WALs at LSN %X/%08X.",
-                                                                 
LSN_FORMAT_ARGS(slot->data.restart_lsn)));
-
-                               skip_reason = SS_SKIP_NO_CONSISTENT_SNAPSHOT;
-                       }
+                       /* A persistent slot must always reach a consistent 
snapshot. */
+                       Assert(found_consistent_snapshot ||
+                                  slot->data.persistency == RS_TEMPORARY);
 
                        /*
                         * It is possible that the slot's xmin or LSNs are not 
updated,
@@ -383,6 +380,26 @@ update_local_synced_slot(RemoteSlot *remote_slot, Oid 
remote_dbid)
                }
        }
 
+       /*
+        * A temporary slot is not sync-ready unless this call confirmed that
+        * decoding from its restart_lsn reaches a consistent point (any 
temporary
+        * slot that reached consistency in an earlier call would already have
+        * been persisted by update_and_persist_local_synced_slot()). That's the
+        * case both when advancing the slot above failed to build a consistent
+        * snapshot and when we skipped advancing because the remote slot has 
not
+        * moved ahead of the local slot.
+        */
+       if (slot->data.persistency == RS_TEMPORARY && 
!found_consistent_snapshot)
+       {
+               ereport(LOG,
+                               errmsg("could not synchronize replication slot 
\"%s\"",
+                                          remote_slot->name),
+                               errdetail("Synchronization could lead to data 
loss, because the standby could not build a consistent snapshot to decode WALs 
at LSN %X/%08X.",
+                                                 
LSN_FORMAT_ARGS(slot->data.restart_lsn)));
+
+               skip_reason = SS_SKIP_NO_CONSISTENT_SNAPSHOT;
+       }
+
        /* Update slot sync skip stats */
        update_slotsync_skip_stats(skip_reason);
 
-- 
2.54.0 (Apple Git-157)

From a20f18566164b467a3ec2f44a5b69ca9a906a6c8 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Mon, 16 Nov 2026 15:43:47 +0800
Subject: [PATCH v3 2/2] Add test for keeping synced slots temporary without a
 consistent snapshot.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Add a TAP test verifying that a synced slot on the standby remains
temporary across multiple synchronization cycles when a consistent
snapshot cannot be built.
---
 .../t/040_standby_failover_slots_sync.pl      | 53 +++++++++++++++++++
 1 file changed, 53 insertions(+)

diff --git a/src/test/recovery/t/040_standby_failover_slots_sync.pl 
b/src/test/recovery/t/040_standby_failover_slots_sync.pl
index b0f4dfad6f2..8272dae95c7 100644
--- a/src/test/recovery/t/040_standby_failover_slots_sync.pl
+++ b/src/test/recovery/t/040_standby_failover_slots_sync.pl
@@ -1114,4 +1114,57 @@ $standby2->wait_for_log(
 
 $h->quit;
 
+##################################################
+# Test that a synced slot stays temporary when the standby cannot build a
+# consistent snapshot across multiple sync cycles.
+##################################################
+
+# Disable the subscription so lsub1_slot does not advance and serialize
+# snapshots on standby2 while still holding back catalog_xmin on standby2.
+$subscriber1->safe_psql('postgres',
+       "ALTER SUBSCRIPTION regress_mysub1 DISABLE");
+$primary->poll_query_until('postgres',
+       "SELECT NOT active FROM pg_replication_slots WHERE slot_name = 
'lsub1_slot'"
+);
+
+$primary->safe_psql('postgres',
+       "SELECT pg_create_logical_replication_slot('inconsistent_slot', 
'test_decoding', false, false, true);"
+);
+
+# Keep a transaction with an assigned XID open while logging xl_running_xacts
+# and advancing inconsistent_slot so its restart_lsn moves to that record and
+# concurrent bgwriter snapshots cannot make it consistent. Advance the slot
+# twice in case a concurrent xl_running_xacts record logged before the open
+# transaction was used as the candidate restart_lsn in the first call.
+my $xact_h = $primary->background_psql('postgres');
+$xact_h->query_safe('BEGIN; SELECT pg_current_xact_id();');
+
+$primary->safe_psql(
+       'postgres', qq(
+       SELECT pg_log_standby_snapshot();
+       BEGIN;
+       INSERT INTO tab_int VALUES (100);
+       COMMIT;
+       SELECT pg_replication_slot_advance('inconsistent_slot', 
pg_current_wal_lsn());
+       SELECT pg_replication_slot_advance('inconsistent_slot', 
pg_current_wal_lsn());
+));
+
+$xact_h->query_safe('COMMIT;');
+$xact_h->quit;
+
+$primary->wait_for_replay_catchup($standby2);
+
+$standby2->append_conf('postgresql.conf', 'sync_replication_slots = on');
+$standby2->reload;
+
+ok( $standby2->poll_query_until(
+               'postgres', qq(
+               SELECT slotsync_skip_count >= 2 AND temporary AND
+                          slotsync_skip_reason = 'no_consistent_snapshot'
+               FROM pg_stat_replication_slots
+               JOIN pg_replication_slots USING (slot_name)
+               WHERE slot_name = 'inconsistent_slot';
+       )),
+       'synced slot without a consistent snapshot stays temporary');
+
 done_testing();
-- 
2.54.0 (Apple Git-157)

Reply via email to