[BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
[BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
Hi hackers, I'd like to report a regression in PostgreSQL 18 regarding physical replication slot invalidation and propose a fix. It's my first time sending any type of contribution, so please let me know if I made anything incorrectly and I'll fix it ASAP. It's also my first time doing any type of code inside the postgres project, so if the logic or anything I used is incorrect let me know. CCing Amit, since he committed f41d8468 and 8709dcc. ## Problem Commit f41d8468 introduced an ERROR when trying to acquire an invalidated replication slot. While this is correct for logical replication slots (which cannot safely recover after invalidation), it breaks recovery for physical replication slots. Later, commit 8709dcc improved upon this code to prevent a race condition and moved the check to after the slot was already acquired. In PostgreSQL 17 and earlier, when a physical replication slot was invalidated due to max_slot_wal_keep_size, the slot could still be reacquired if the required WAL became available through restore_command or archive recovery in the standby. This is a common operational scenario: - Temporary network issues - Planned maintenance windows - Standbys temporarily falling behind After commit f41d8468, physical replication slots cannot be reacquired once invalidated, even when the required WAL is available via archive recovery. The standby remains stuck recovering from archive and cannot resume streaming replication, demanding manual intervention (slot recreation). ## Reproduction 1. Set up primary with physical replication slot and small max_slot_wal_keep_size 2. Configure standby with restore_command for archive recovery 3. Stop standby and generate enough WAL on primary to invalidate the slot 4. Restart standby - it can access WAL from archive but gets: "FATAL: can no longer access replication slot" In PG17, streaming would resume. In PG18, it stays permanently broken. ## Proposed Fix The attached patch differentiates between logical and physical slots in ReplicationSlotAcquire(): - Logical slots: Raise ERROR as before (cannot safely recover) - Physical slots: Log a warning but allow acquisition (can recover) This restores the PG17 behavior for physical slots while maintaining safety guarantees for logical slots. The patch includes a TAP test that: - Demonstrates the issue - Verifies the fix works - Ensures physical slots can recover after invalidation ## Testing Tested on both master and REL_18_STABLE: - All existing regression tests pass - New TAP test passes - Manual testing confirms standbys can recover ## Backpatching This should be backpatched to PostgreSQL 18 where the regression was introduced. Patches attached: - v1-0001-Allow-physical-replication-slots-to-recover-after-invalidation.patch (for master) - v1-0001-Allow-physical-replication-slots-to-recover-after-invalidation-pg18.patch (for REL_18_STABLE) Best regards, Joao Foltran
RE: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
От:
"Zhijie Hou (Fujitsu)" <houzj.fnst@fujitsu.com>
Дата:
On Tuesday, December 16, 2025 2:54 AM Joao Foltran wrote: > Hi hackers, > > I'd like to report a regression in PostgreSQL 18 regarding physical replication > slot invalidation and propose a fix. > > It's my first time sending any type of contribution, so please let me know if I > made anything incorrectly and I'll fix it ASAP. > > It's also my first time doing any type of code inside the postgres project, so if > the logic or anything I used is incorrect let me know. > > CCing Amit, since he committed f41d8468 and 8709dcc. > > ## Problem > > Commit f41d8468 introduced an ERROR when trying to acquire an invalidated > replication slot. While this is correct for logical replication slots (which cannot > safely recover after invalidation), it breaks recovery for physical replication > slots. > > Later, commit 8709dcc improved upon this code to prevent a race condition > and moved the check to after the slot was already acquired. > > In PostgreSQL 17 and earlier, when a physical replication slot was invalidated > due to max_slot_wal_keep_size, the slot could still be reacquired if the > required WAL became available through restore_command or archive > recovery in the standby. This is a common operational scenario: > > - Temporary network issues > - Planned maintenance windows > - Standbys temporarily falling behind I think the ability to acquire an invalidated slot represents an potentially risky behavior. AFAICS, we do not currently support recovering invalidated slots. This implies that once a slot becomes invalidated, it does not offer any protection anymore. Even if the restart_lsn or xmin is valid for such a slot, WAL and rows can be removed at any time. For further clarification, please refer to ReplicationSlotsComputeRequiredLSN(), where we deliberately exclude counting the restart_lsn for an invalidated slot. > > After commit f41d8468, physical replication slots cannot be reacquired once > invalidated, even when the required WAL is available via archive recovery. > The standby remains stuck recovering from archive and cannot resume > streaming replication, demanding manual intervention (slot recreation). > I think even if the WALs is temporary available via archive recovery, since the slot cannot protect any further WALs and rows from being removed, it could cause problems later. Best Regards, Hou zj
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
От:
Joao Foltran <joao@foltrandba.com>
Дата:
Hi Zhijie,
Thank you for clarifying this behavior to me! I've tested it and it
really doesn't hold back wals anymore once it has been invalidated due
to the check inside ReplicationSlotsComputeRequiredLSN().
You are correct that simply letting the slot be reacquired and
continue working would be dangerous leading to possibly losing WALs.
Can we then check if the standby was able to reconnect and start
streaming successfully and then change the slots information for it to
be considered inside ReplicationSlotsComputeRequiredLSN() again?
Example:
in XLogSendPhysical(), after we seen that the first record was sent:
// In XLogSendPhysical() after XLogReadRecord() succeeds
if (first_record_sent &&
MyReplicationSlot &&
SlotIsPhysical(MyReplicationSlot) &&
MyReplicationSlot->data.invalidated != RS_INVAL_NONE)
{
// Clear invalidation - we successfully read WAL
}
This would clear the invalidation only after we know for sure that it
can continue streaming wals without problem.
After we clear the invalidation then the slot should be able to start
holding back wals again, right?
Regards,
Joao Foltran
On Tue, Dec 16, 2025 at 12:15 AM Zhijie Hou (Fujitsu)
wrote:
>
> On Tuesday, December 16, 2025 2:54 AM Joao Foltran wrote:
> > Hi hackers,
> >
> > I'd like to report a regression in PostgreSQL 18 regarding physical replication
> > slot invalidation and propose a fix.
> >
> > It's my first time sending any type of contribution, so please let me know if I
> > made anything incorrectly and I'll fix it ASAP.
> >
> > It's also my first time doing any type of code inside the postgres project, so if
> > the logic or anything I used is incorrect let me know.
> >
> > CCing Amit, since he committed f41d8468 and 8709dcc.
> >
> > ## Problem
> >
> > Commit f41d8468 introduced an ERROR when trying to acquire an invalidated
> > replication slot. While this is correct for logical replication slots (which cannot
> > safely recover after invalidation), it breaks recovery for physical replication
> > slots.
> >
> > Later, commit 8709dcc improved upon this code to prevent a race condition
> > and moved the check to after the slot was already acquired.
> >
> > In PostgreSQL 17 and earlier, when a physical replication slot was invalidated
> > due to max_slot_wal_keep_size, the slot could still be reacquired if the
> > required WAL became available through restore_command or archive
> > recovery in the standby. This is a common operational scenario:
> >
> > - Temporary network issues
> > - Planned maintenance windows
> > - Standbys temporarily falling behind
>
> I think the ability to acquire an invalidated slot represents an
> potentially risky behavior. AFAICS, we do not currently support
> recovering invalidated slots. This implies that once a slot becomes invalidated,
> it does not offer any protection anymore. Even if the restart_lsn or xmin is valid for
> such a slot, WAL and rows can be removed at any time. For further clarification,
> please refer to ReplicationSlotsComputeRequiredLSN(), where we deliberately
> exclude counting the restart_lsn for an invalidated slot.
>
> >
> > After commit f41d8468, physical replication slots cannot be reacquired once
> > invalidated, even when the required WAL is available via archive recovery.
> > The standby remains stuck recovering from archive and cannot resume
> > streaming replication, demanding manual intervention (slot recreation).
> >
>
> I think even if the WALs is temporary available via archive recovery, since the slot
> cannot protect any further WALs and rows from being removed, it could cause
> problems later.
>
> Best Regards,
> Hou zj
>
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Dec 16, 2025 at 9:54 AM Joao Foltran wrote:
>
> Thank you for clarifying this behavior to me! I've tested it and it
> really doesn't hold back wals anymore once it has been invalidated due
> to the check inside ReplicationSlotsComputeRequiredLSN().
>
> You are correct that simply letting the slot be reacquired and
> continue working would be dangerous leading to possibly losing WALs.
> Can we then check if the standby was able to reconnect and start
> streaming successfully and then change the slots information for it to
> be considered inside ReplicationSlotsComputeRequiredLSN() again?
>
> Example:
>
> in XLogSendPhysical(), after we seen that the first record was sent:
>
> // In XLogSendPhysical() after XLogReadRecord() succeeds
> if (first_record_sent &&
> MyReplicationSlot &&
> SlotIsPhysical(MyReplicationSlot) &&
> MyReplicationSlot->data.invalidated != RS_INVAL_NONE)
> {
> // Clear invalidation - we successfully read WAL
> }
>
> This would clear the invalidation only after we know for sure that it
> can continue streaming wals without problem.
>
The slots could be invalidated due to other reasons like
RS_INVAL_IDLE_TIMEOUT as well. It doesn't sound like a good to clear
the invalidation flag of the slot because tomorrow we could decide to
invalidate due to other reasons as well. I think it would be better to
do the required forensic with invalid slots and re-create the slot if
we want to retain the required WAL. Why don't you prefer to re-create
it once the slot is invalidated?
--
With Regards,
Amit Kapila.
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
От:
Joao Foltran <joao@foltrandba.com>
Дата:
> The slots could be invalidated due to other reasons like
> RS_INVAL_IDLE_TIMEOUT as well.
We could just filter which invalidation reasons could be "revalidated"
for only reasons that can be resolved this way.
As for recreating vs not recreating the slots: in situations where you
have tons of clusters that have disk space constraints this would help
tremendously. There's probably a lot of users that would prefer
self-healing in situations it can happen.
Self-healing doesn't mean not reporting it. They can later check the
reason in the logs why it happened and prevent it from happening in
the future.
If making this the default, it could be a flag in the slot? Something
like "self-healing: true", this way any possible self-healing
operations are enabled for the slot, this would enable for new
self-healing enhancements in the future to also be behind a flag and
prevent it from running when someone prefers error+investigate instead
of self-heal+investigate.
--
Regards,
João Foltran
On Tue, Dec 16, 2025 at 6:15 AM Amit Kapila wrote:
>
> On Tue, Dec 16, 2025 at 9:54 AM Joao Foltran wrote:
> >
> > Thank you for clarifying this behavior to me! I've tested it and it
> > really doesn't hold back wals anymore once it has been invalidated due
> > to the check inside ReplicationSlotsComputeRequiredLSN().
> >
> > You are correct that simply letting the slot be reacquired and
> > continue working would be dangerous leading to possibly losing WALs.
> > Can we then check if the standby was able to reconnect and start
> > streaming successfully and then change the slots information for it to
> > be considered inside ReplicationSlotsComputeRequiredLSN() again?
> >
> > Example:
> >
> > in XLogSendPhysical(), after we seen that the first record was sent:
> >
> > // In XLogSendPhysical() after XLogReadRecord() succeeds
> > if (first_record_sent &&
> > MyReplicationSlot &&
> > SlotIsPhysical(MyReplicationSlot) &&
> > MyReplicationSlot->data.invalidated != RS_INVAL_NONE)
> > {
> > // Clear invalidation - we successfully read WAL
> > }
> >
> > This would clear the invalidation only after we know for sure that it
> > can continue streaming wals without problem.
> >
>
> The slots could be invalidated due to other reasons like
> RS_INVAL_IDLE_TIMEOUT as well. It doesn't sound like a good to clear
> the invalidation flag of the slot because tomorrow we could decide to
> invalidate due to other reasons as well. I think it would be better to
> do the required forensic with invalid slots and re-create the slot if
> we want to retain the required WAL. Why don't you prefer to re-create
> it once the slot is invalidated?
>
> --
> With Regards,
> Amit Kapila.
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Jan 6, 2026 at 3:26 AM Joao Foltran wrote: > > > The slots could be invalidated due to other reasons like > > RS_INVAL_IDLE_TIMEOUT as well. > > We could just filter which invalidation reasons could be "revalidated" > for only reasons that can be resolved this way. > Can we make the slot valid even the required WAL is made available afterwards? What about the removed rows due to the slot's xmin? -- With Regards, Amit Kapila.
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
Hi Amit! Unless we have hot_standby_feedback = on, xmin would be null on the physical replication slot. But, even if using that parameter, as long as we know that the standby already has caught up by using the archived wals then the xmin wouldn't matter, since we don't need those rows to be visible anymore. I've attached a simple patch and test here that revalidates the slot after it is lost. It is still missing any filtering besides checking if the slot is physical or logical, but we can add filters for specific invalidations. Let me know what you think. Regards, João Foltran On Wed, Jan 14, 2026 at 8:21 AM Amit Kapila wrote: > > On Tue, Jan 6, 2026 at 3:26 AM Joao Foltran wrote: > > > > > The slots could be invalidated due to other reasons like > > > RS_INVAL_IDLE_TIMEOUT as well. > > > > We could just filter which invalidation reasons could be "revalidated" > > for only reasons that can be resolved this way. > > > > Can we make the slot valid even the required WAL is made available > afterwards? What about the removed rows due to the slot's xmin? > > -- > With Regards, > Amit Kapila.
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
Hello all, I've made a v2 of this patch, turning it into a patchset with guidance from Fabrizio Mello. This patchset includes a new feature that self-heals (auto revalidates) physical replication slots after they have been invalidated for two reasons: RS_INVAL_WAL_REMOVED or RS_INVAL_IDLE_TIMEOUT. Requiring an user to manually recreate slot isn't necessary in cases where the standby server connected to these slots recovers itself using restore_command and can become burdensome when managing a fleet of clusters, creating a need to handle this kind of problem automatically due to the scale of your operation. The patch adds a opt-in mechanism that allows the physical slots to be reinvalidated in those cases, a new persistent field called `auto_revalidate` (default false) controls which physical slots are eligible. When enabled, StartReplication issues a WARNING instead of an ERROR when acquiring physical invalidated slots and PhysicalConfirmReceivedLocation clears the invalidation atomically with the restart_lsn update upon the first flush ACK. The revalidation is persisted to disk immediately so it survives a crash. Only RS_INVAL_WAL_REMOVED and RS_INVAL_IDLE_TIMEOUT revalidatable, via an explicit allowlist in SlotCanBeRevalidated(). Future invalidation reasons must be added there to become eligible. I appreciate Fabrizio's help reviewing everything and walking me through my questions. The series is split into five patches: 0001 - Core infrastructure: SlotCanBeRevalidated helper, SlotIsValid macro, revalidation logic in walsender.c, SLOT_VERSION bump. 0002 - SQL function: new auto_revalidate parameter on pg_create_physical_replication_slot(), copy-path propagation via pg_copy_physical_replication_slot(), regression test. 0003 - View exposure: auto_revalidate column in pg_replication_slots. 0004 - TAP recovery test: six scenarios covering revalidation, WAL retention, xmin recovery, error preservation for auto_revalidate=false, slot copy revalidation, and idle_timeout revalidation (some of these require injection_points). 0005 - Documentation: system-views.sgml and func-admin.sgml. João Foltran Linkedin: https://www.linkedin.com/in/joao-foltran-031b9312b On Thu, Jan 22, 2026 at 4:41 PM Joao Foltran wrote: > > Hi Amit! > > Unless we have hot_standby_feedback = on, xmin would be null on the > physical replication slot. > > But, even if using that parameter, as long as we know that the standby > already has caught up by using the archived wals then the xmin > wouldn't matter, since we don't need those rows to be visible anymore. > > I've attached a simple patch and test here that revalidates the slot > after it is lost. It is still missing any filtering besides checking > if the slot is physical or logical, but we can add filters for > specific invalidations. > > Let me know what you think. > > Regards, > João Foltran > > On Wed, Jan 14, 2026 at 8:21 AM Amit Kapila wrote: > > > > On Tue, Jan 6, 2026 at 3:26 AM Joao Foltran wrote: > > > > > > > The slots could be invalidated due to other reasons like > > > > RS_INVAL_IDLE_TIMEOUT as well. > > > > > > We could just filter which invalidation reasons could be "revalidated" > > > for only reasons that can be resolved this way. > > > > > > > Can we make the slot valid even the required WAL is made available > > afterwards? What about the removed rows due to the slot's xmin? > > > > -- > > With Regards, > > Amit Kapila.
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
I've rebased onto the current master branch and applied this patch to the commitfest. Resolved a test-numbering conflict, no logic changes were made. João Foltran
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
Fixed the TAP test because a timing condition affected its execution in the CI. JOÃO FOLTRAN
Re: [BUG] [PATCH] Allow physical replication slots to recover from archive after invalidation
Hi Sravan,
Thanks a lot for the detailed review. Attached is v5, which addresses
your comments. Details below.
> The fix produces an additional discrepancy in the slot status,
> which is very unlikely to occur, through a phantom false clear.
> A buffered 'r' reply from downstream can revalidate a slot for
> a short duration before its invalidation again when the WAL is
> not found. [...] It may be worth looking at how we can avoid
> it, possibly by clearing the flag on a successful
> restart_lsn advancement past the invalidation point, or after a
> successful WAL send.
Fixed in v5, following the second of your two suggestions in a
slightly stronger form: a successful WAL send plus a confirmation
that the standby received it.
The walsender now keeps a per-session target LSN (revalidationTargetPtr),
invalid until XLogSendPhysical() establishes it, once per session:
- If there is WAL to send, the target is the end LSN of the first
WAL data message queued. Queueing it proves WALRead() succeeded,
so for wal_removed the required WAL demonstrably exists.
- If the standby is already caught up (SendRqstPtr <= sentPtr), the
target is the current send position. Since the qualifying reply may
have already been processed (the initial status reply) and a
caught-up standby may never send another one, the confirmed flush
position is rechecked immediately at that point.
PhysicalConfirmReceivedLocation() clears the invalidation only when a
flush ACK covers the target, atomically with the restart_lsn update
under the slot spinlock, and persists the slot right away. A buffered
'r' processed before the target exists can no longer revalidate the
slot, so the phantom false clear and its misleading log line are gone.
I went with send-plus-ACK rather than restart_lsn advancement past the
invalidation point because the latter defers revalidation indefinitely
in a common case: after an idle_timeout invalidation the standby is
typically fully caught up, so on reconnect restart_lsn has nothing to
advance past until new WAL is generated, and the slot would sit
active-but-invalid on an idle primary even though the standby verifiably
holds everything. The ACK-covers-target gate provides the same
protection against the stray-'r' problem without that deferral. The
caught-up case cannot produce a phantom either: the confirmed flush
position covers all WAL the server has, so there is nothing left to
read that could subsequently fail and re-invalidate the slot.
> For a slot that is revalidatable but not recoverable, during the
> window between slot acquire and the first flush acknowledgement,
> the slot will show up as active while invalid for a slightly
> longer period, and continues to happen on every retry. To report
> correctly during such windows, we can check for WAL availability
> before slot acquire (before going active).
I looked at this but left it out of v5. A pre-acquire availability
check is inherently racy, a checkpoint can remove the WAL between
the check and the first read, as you noted yourself for the
recoverable case, so it can shorten the window but not close it,
at the cost of an extra probe on a path that is retried anyway. I am
not opposed to it as an incremental improvement if the window proves
bothersome in practice.
> Can we consider allowing auto_revalidate via a GUC - to provide
> the option across a fleet of slots, for convenience?
I would prefer to keep it per-slot for now: a GUC would change the
invalidation contract of slots whose owners may not expect it, and
the interaction between a reloadable global setting and the per-slot
flag needs its own discussion, it would also increase the scope of this patch.
It could be added later on top of this series if there is demand.
Happy to hear other opinions.
> So: is the intended contract of ReplicationSlotAcquire() to be the
> central invalidation gatekeeper [...] or an acquisition mechanism,
> in which case the invalidation policy (error/warn/attempt) could
> stay with each caller and only the error message be single-sourced
> via a small shared helper? [...] I lean toward the shared-helper
> approach, but I think the contract is the authors' call.
Agreed, and v5 takes the shared-helper approach you lean toward.
slot.c now exports ReplicationSlotInvalidationError(), which both
ReplicationSlotAcquire() (for error_if_invalid) and StartReplication()
(for the non-revalidatable branch) use, preserving the message consistency
goal of f41d8468. ReplicationSlotAcquire() stays a plain acquisition
mechanism and the revalidation policy lives entirely in the walsender.
Thanks also for confirming the retry behavior for unrecoverable slots,
and for checking the pg_receivewal, pg_basebackup, and upgrade angles.
I agree there is nothing to do there. One side effect of the new gate
worth mentioning: a caught-up standby now revalidates promptly on
reconnect instead of waiting for new WAL, so the documentation in
0005 was updated accordingly.
The docs in 0001/0005 and the commit messages were updated to describe
the new gating. All recovery TAP tests pass, including the new
056_auto_revalidate_physical_slot.pl.
--
Best regards,
João Foltran