Introduce XID age based replication slot invalidation
Introduce XID age based replication slot invalidation
Hi folks, I'd like to restart the discussion about providing an xid-based slot invalidation mechanism. The previous effort [1] presented an XID and time-based invalidation and the inactive time-based approach was implemented first. The latest XID based patch from Bharath Rupireddy can be found here [2]. When thinking about availability of the database, inactive replication slots cause two main pain points: 1) WAL accumulation 2) Replication slots with xmin/catalog_xmin can hold back vacuuming leading to wrap-around The first issue can be mitigated by 'max_slot_wal_keep_size'. However in the second case there are no good mechanisms to prioritize write availability of the database and avoid wraparound. The new GUC 'idle_replication_slot_timeout' partially addresses the concern if you have similar workloads. However it's hard to set the same setting across a fleet of different applications. It's easy to imagine a high-XID churning workload in one cluster while another has large batch jobs where changes get synced out periodically. There isn't a "one-size" fits all setting for 'idle_replication_slot_timeout' in these two cases. The attached patch addresses this by introducing 'max_slot_xid_age' in a similar fashion. Replication slots with transaction ID greater than the set age will get invalidated allowing vacuum to proceed, biasing towards database availability. Invalidation happens in CHECKPOINT, similar to 'idle_replication_slot_timeout', and when VACUUM occurs. The patch currently attempts to invalidate once-per-autovacuum worker. We're wondering if it should attempt invalidation on a per-relation basis within the vacuum call itself. That would account for scenarios where the cost_delay or naptime is high between autovac executions. Thanks, John H [1] https://www.postgresql.org/message-id/flat/CALj2ACW4aUe-_uFQOjdWCEN-xXoLGhmvRFnL8SNw_TZ5nJe%2Baw%40mail.gmail.com [2] https://www.postgresql.org/message-id/flat/CALj2ACXe8%2BxSNdMXTMaSRWUwX7v61Ad4iddUwnn%3DdjSwx3GLLg%40mail.gmail.com -- John Hsu - Amazon Web Services
RE: Introduce XID age based replication slot invalidation
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear John, > The first issue can be mitigated by 'max_slot_wal_keep_size'. However > in the second case there are no good mechanisms to prioritize write > availability of the database and avoid wraparound. The new GUC > 'idle_replication_slot_timeout' partially addresses the concern if you > have similar workloads. However it's hard to set the same setting > across a fleet of different applications. IIUC, the feature can directly avoid the wraparound issue than other invalidation mechanism. The motivation seems enough for me. > The patch currently attempts to invalidate once-per-autovacuum worker. > We're wondering if it should attempt invalidation on a per-relation > basis within the vacuum call itself. That would account for scenarios > where the cost_delay or naptime is high between autovac executions. I have a concern that age calculation acquire the lock for XidGenLock thus performance can be affected. Do you have insights for it? > > Invalidation happens in CHECKPOINT, similar to > 'idle_replication_slot_timeout', and when VACUUM occurs. Let me confirm because I'm new. VACUUM can also trigger because old XID make VACUUM fail, right? Timeout is aimed for WAL thus it is not so related with VACUUM, which does not recycle segments. In contrast, is there a possibility that XID-age check can be done only at VACUUM? Regarding the patch, try_replication_slot_invalidation() and ReplicationSlotIsXIDAged() do the same task. Can we reduce duplicated part? Best regards, Hayato Kuroda FUJITSU LIMITED
Re: Introduce XID age based replication slot invalidation
Hi Hayato, Thank you for taking a look. > > The patch currently attempts to invalidate once-per-autovacuum worker. > > We're wondering if it should attempt invalidation on a per-relation > > basis within the vacuum call itself. That would account for scenarios > > where the cost_delay or naptime is high between autovac executions. > > I have a concern that age calculation acquire the lock for XidGenLock thus > performance can be affected. Do you have insights for it? Are you concerned if we did the check on a per table case? Or in the current situation where it's only once per-worker. > > > > Invalidation happens in CHECKPOINT, similar to > > 'idle_replication_slot_timeout', and when VACUUM occurs. > > Let me confirm because I'm new. VACUUM can also trigger because old XID make > VACUUM fail, right? Timeout is aimed for WAL thus it is not so related with VACUUM, > which does not recycle segments. > I feel that the timeout is used as a way to roughly address storage accumulation or VACUUM not progressing due to slots. > In contrast, is there a possibility that XID-age check can be done only at VACUUM? It's also done in CHECKPOINT because there can be stale replication slots on standby that aren't there on writer. We would still want them to be invalidated. > Regarding the patch, try_replication_slot_invalidation() and ReplicationSlotIsXIDAged() > do the same task. Can we reduce duplicated part? Thanks for catching, I thought I did this but guess not. Updated in the latest attachment. -- John Hsu - Amazon Web Services
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Thu, Sep 18, 2025 at 10:20 AM John H wrote: > > I'd like to restart the discussion about providing an xid-based slot > invalidation mechanism. The previous effort [1] presented an XID and > time-based invalidation and the inactive time-based approach was > implemented first. The latest XID based patch from Bharath Rupireddy > can be found here [2]. > > When thinking about availability of the database, inactive replication > slots cause two main pain points: > 1) WAL accumulation > 2) Replication slots with xmin/catalog_xmin can hold back vacuuming > leading to wrap-around > > It's easy to imagine a high-XID churning workload in one cluster while > another has large batch jobs where changes get synced out > periodically. There isn't a "one-size" fits all setting for > 'idle_replication_slot_timeout' in these two cases. +1. > The attached patch addresses this by introducing 'max_slot_xid_age' in > a similar fashion. Replication slots with transaction ID greater than > the set age will get invalidated allowing vacuum to proceed, biasing > towards database availability. > > Invalidation happens in CHECKPOINT, similar to > 'idle_replication_slot_timeout', and when VACUUM occurs. > > The patch currently attempts to invalidate once-per-autovacuum worker. > We're wondering if it should attempt invalidation on a per-relation > basis within the vacuum call itself. That would account for scenarios > where the cost_delay or naptime is high between autovac executions. IMO, computing XID horizons per-relation during vacuum is good. The main reason we try to invalidate replication slots based on the XID age in the vacuum path is to help the database when it needs it most - when vacuum is computing the XID horizons. That said, it would be good to have performance analysis with a large number of replication slots, comparing once-per-relation vs. once-per-autovacuum worker vs. once-per-autovacuum launcher wake-up cycle. I haven't looked at the patch in depth, but it would be good to have a TAP test with more realistic production workloads. We could set this value to less than 1.5 billion and use xid_wraparound test to quickly reach the wraparound limits, then verify if this setting can help prevent the database from reaching wraparound errors. This approach would also validate the age calculations in try_replication_slot_invalidation with higher limits. -- Bharath Rupireddy PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi John, Thank you for sending in the rebased patch earlier. I will have some cycles going forward and I would like to continue with this work. Hi Kuroda-san, Thank you for reviewing the patch. On Fri, Sep 19, 2025 at 1:07 AM Hayato Kuroda (Fujitsu) wrote: > > IIUC, the feature can directly avoid the wraparound issue than other > invalidation mechanism. The motivation seems enough for me. That's correct. When enabled, replication slots whose XID age exceeds the configured value get invalidated before vacuum computes the XID horizons. This ensures that slots which would otherwise prevent vacuum from freezing heap tuples don't come in the way of XID wraparound prevention. > The patch currently attempts to invalidate once-per-autovacuum worker. > We're wondering if it should attempt invalidation on a per-relation > basis within the vacuum call itself. That would account for scenarios > where the cost_delay or naptime is high between autovac executions. > > I have a concern that age calculation acquire the lock for XidGenLock thus > performance can be affected. Do you have insights for it? I made the following design choice: try invalidating only once per vacuum cycle, not per table. While this keeps the cost of checking (incl. the XidGenLock contention) for invalidation to a minimum when there are a large number of tables and replication slots, it can be less effective when individual tables/indexes are large. Invalidating during checkpoints can help to some extent with the large table/index cases. But I'm open to thoughts on this. Please find the attached patch for further review. I fixed the XID age calculation in ReplicationSlotIsXIDAged and adjusted the code comments. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
SATYANARAYANA NARLAPURAM <satyanarlapuram@gmail.com>
Дата:
Hi Bharath,
Do you think we need different GUCs for catalog_xmin and xmin? If table bloat is a concern (not catalog bloat), then logical slots are not required to invalidate unless the cluster is close to wraparound.
I made the following design choice: try invalidating only once per
vacuum cycle, not per table. While this keeps the cost of checking
(incl. the XidGenLock contention) for invalidation to a minimum when
there are a large number of tables and replication slots, it can be
less effective when individual tables/indexes are large. Invalidating
during checkpoints can help to some extent with the large table/index
cases. But I'm open to thoughts on this.
It may not solve the intent when the vacuum cycle is longer, which one can expect on a large database particularly when there is heavy bloat.
Please find the attached patch for further review. I fixed the XID age
calculation in ReplicationSlotIsXIDAged and adjusted the code
comments.
I applied the patch and all the tests passed. A few comments:
@@ -495,7 +525,7 @@ vacuum(List *relations, const VacuumParams params, BufferAccessStrategy bstrateg
MemoryContext vac_context, bool isTopLevel)
{
static bool in_vacuum = false;
-
+ static bool first_time = true;
MemoryContext vac_context, bool isTopLevel)
{
static bool in_vacuum = false;
-
+ static bool first_time = true;
first_time variable is not self explanatory, maybe something like try_replication_slot_invalidation and add comments that it will be set to false after the first check?
+ if (TransactionIdIsValid(xmin))
+ appendStringInfo(&err_detail, _("The slot's xmin %u exceeds the maximum xid age %d specified by \"max_slot_xid_age\"."),
+ xmin,
+ max_slot_xid_age);
+ appendStringInfo(&err_detail, _("The slot's xmin %u exceeds the maximum xid age %d specified by \"max_slot_xid_age\"."),
+ xmin,
+ max_slot_xid_age);
Slot invalidates even when the age is max_slot_xid_age, isn't it?
Thanks,
Satya
Re: Introduce XID age based replication slot invalidation
Hi,
On Fri, Mar 20, 2026 at 11:29 PM SATYANARAYANA NARLAPURAM
wrote:
>
> Do you think we need different GUCs for catalog_xmin and xmin? If table bloat is a concern (not catalog bloat), then logical slots are not required to invalidate unless the cluster is close to wraparound.
IMO the main purpose of max_slot_xid_age is to prevent XID wraparound.
For bloat, I still think max_slot_wal_keep_size is the better choice.
Where max_slot_xid_age is really useful is when the vacuum can't
freeze because a replication slot (physical or logical) is holding
back the XID horizon and the system is getting close to wraparound.
Invalidating such a slot clears the way for vacuum. Setting
max_slot_xid_age above vacuum_failsafe_age allows vacuum to waste
cycles scanning tables it cannot freeze. Keeping max_slot_xid_age <=
vacuum_failsafe_age (default 1.6B) prevents this by invalidating the
slot before vacuum effort is wasted.
As far as XID wraparound is concerned, both xmin and catalog_xmin need
to be treated similarly. Either one can hold back freezing and push
the system toward wraparound. So I don't think we need separate GUCs
for xmin and catalog_xmin unless I'm missing something. One GUC
covering both keeps things simple.
>> I made the following design choice: try invalidating only once per
>> vacuum cycle, not per table. While this keeps the cost of checking
>> (incl. the XidGenLock contention) for invalidation to a minimum when
>> there are a large number of tables and replication slots, it can be
>> less effective when individual tables/indexes are large. Invalidating
>> during checkpoints can help to some extent with the large table/index
>> cases. But I'm open to thoughts on this.
>
> It may not solve the intent when the vacuum cycle is longer, which one can expect on a large database particularly when there is heavy bloat.
This design choice boils down to the following: a database instance
having either 1/ a large number of small tables or 2/ large tables.
From my experience, I have seen both cases but mostly case 2 (others
can correct me). In this context, having an XID age based slot
invalidation check once per relation makes sense. However, I'm open to
more thoughts here.
>> Please find the attached patch for further review. I fixed the XID age
>> calculation in ReplicationSlotIsXIDAged and adjusted the code
>> comments.
>
> I applied the patch and all the tests passed. A few comments:
Thank you for reviewing the patch.
> @@ -495,7 +525,7 @@ vacuum(List *relations, const VacuumParams params, BufferAccessStrategy bstrateg
> MemoryContext vac_context, bool isTopLevel)
> {
> static bool in_vacuum = false;
> -
> + static bool first_time = true;
>
> first_time variable is not self explanatory, maybe something like try_replication_slot_invalidation and add comments that it will be set to false after the first check?
+1. Changed the variable name and simplified the comments around.
> + if (TransactionIdIsValid(xmin))
> + appendStringInfo(&err_detail, _("The slot's xmin %u exceeds the maximum xid age %d specified by \"max_slot_xid_age\"."),
> + xmin,
> + max_slot_xid_age);
>
> Slot invalidates even when the age is max_slot_xid_age, isn't it?
Nice catch! I changed it to use TransactionIdPrecedes so it matches
the above error message like the two of the existing XID age GUCs
(autovacuum_freeze_max_age, vacuum_failsafe_age).
Please find the attached v2 patch for further review. Thank you!
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Hi, On Mon, Mar 23, 2026 at 9:00 AM Bharath Rupireddy wrote: > > Hi, > > On Fri, Mar 20, 2026 at 11:29 PM SATYANARAYANA NARLAPURAM > wrote: > > > > Do you think we need different GUCs for catalog_xmin and xmin? If table bloat is a concern (not catalog bloat), then logical slots are not required to invalidate unless the cluster is close to wraparound. > > IMO the main purpose of max_slot_xid_age is to prevent XID wraparound. > For bloat, I still think max_slot_wal_keep_size is the better choice. > > Where max_slot_xid_age is really useful is when the vacuum can't > freeze because a replication slot (physical or logical) is holding > back the XID horizon and the system is getting close to wraparound. > Invalidating such a slot clears the way for vacuum. Setting > max_slot_xid_age above vacuum_failsafe_age allows vacuum to waste > cycles scanning tables it cannot freeze. Keeping max_slot_xid_age <= > vacuum_failsafe_age (default 1.6B) prevents this by invalidating the > slot before vacuum effort is wasted. > > As far as XID wraparound is concerned, both xmin and catalog_xmin need > to be treated similarly. Either one can hold back freezing and push > the system toward wraparound. So I don't think we need separate GUCs > for xmin and catalog_xmin unless I'm missing something. One GUC > covering both keeps things simple. I've studied the discussion on this thread and the patch. I understand the purpose of this feature and agree that it's useful especially in cases where orphaned (physical or logical) replication slots prevent the xmin from advancing and inactive_since based slot invalidation might not fit. And +1 for treating both the slot's xmin and catalog_xmin similarly with the single GUC. > >> I made the following design choice: try invalidating only once per > >> vacuum cycle, not per table. While this keeps the cost of checking > >> (incl. the XidGenLock contention) for invalidation to a minimum when > >> there are a large number of tables and replication slots, it can be > >> less effective when individual tables/indexes are large. Invalidating > >> during checkpoints can help to some extent with the large table/index > >> cases. But I'm open to thoughts on this. > > > > It may not solve the intent when the vacuum cycle is longer, which one can expect on a large database particularly when there is heavy bloat. > > This design choice boils down to the following: a database instance > having either 1/ a large number of small tables or 2/ large tables. > From my experience, I have seen both cases but mostly case 2 (others > can correct me). In this context, having an XID age based slot > invalidation check once per relation makes sense. However, I'm open to > more thoughts here. ISTM that checking the XID-based slot invalidation per table would be more bullet-proof and cover many cases. How about checking the XID-based slot invalidation opportunity only when the OldestXmin is older than the new GUC? For example, we can do this check in heap_vacuum_rel() based on the VacuumCutoffs returned by vacuum_get_cutoffs(). If we invalidate at least one slot for its XID, we can re-compute the OldestXmin. Regards, -- Masahiko Sawada Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi, On Mon, Mar 23, 2026 at 4:36 PM Masahiko Sawada wrote: > > I've studied the discussion on this thread and the patch. I understand > the purpose of this feature and agree that it's useful especially in > cases where orphaned (physical or logical) replication slots prevent > the xmin from advancing and inactive_since based slot invalidation > might not fit. > > And +1 for treating both the slot's xmin and catalog_xmin similarly > with the single GUC. Thanks for reviewing the patch. > > >> I made the following design choice: try invalidating only once per > > >> vacuum cycle, not per table. While this keeps the cost of checking > > >> (incl. the XidGenLock contention) for invalidation to a minimum when > > >> there are a large number of tables and replication slots, it can be > > >> less effective when individual tables/indexes are large. Invalidating > > >> during checkpoints can help to some extent with the large table/index > > >> cases. But I'm open to thoughts on this. > > > > > > It may not solve the intent when the vacuum cycle is longer, which one can expect on a large database particularly when there is heavy bloat. > > > > This design choice boils down to the following: a database instance > > having either 1/ a large number of small tables or 2/ large tables. > > From my experience, I have seen both cases but mostly case 2 (others > > can correct me). In this context, having an XID age based slot > > invalidation check once per relation makes sense. However, I'm open to > > more thoughts here. > > ISTM that checking the XID-based slot invalidation per table would be > more bullet-proof and cover many cases. How about checking the > XID-based slot invalidation opportunity only when the OldestXmin is > older than the new GUC? For example, we can do this check in > heap_vacuum_rel() based on the VacuumCutoffs returned by > vacuum_get_cutoffs(). If we invalidate at least one slot for its XID, > we can re-compute the OldestXmin. Agreed. Here's the patch that moves the XID-age based slot invalidation check to vacuum_get_cutoffs. This has some nice advantages: 1/ It makes the check once per table (to help with large tables). 2/ It makes the check less costly since we rely on already computed OldestXmin and nextXID values. 3/ It avoids the checkpointer to do XID-age based slot invalidation which keeps the usage of this GUC simple with no additional costs to the checkpointer - just the vacuum (both vacuum command and autovacuum) does the invalidation when needed. I moved the new tests to the existing TAP test file t/019_replslot_limit.pl alongside other invalidation tests. I added detailed comments around InvalidateXIDAgedReplicationSlots and slightly modified the docs. Please find the v3 patch for further review. PS: Thanks Sawada-san for the offlist chat. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Mar 24, 2026 at 2:42 PM Bharath Rupireddy
wrote:
>
> Hi,
>
> On Mon, Mar 23, 2026 at 4:36 PM Masahiko Sawada wrote:
> >
> > I've studied the discussion on this thread and the patch. I understand
> > the purpose of this feature and agree that it's useful especially in
> > cases where orphaned (physical or logical) replication slots prevent
> > the xmin from advancing and inactive_since based slot invalidation
> > might not fit.
> >
> > And +1 for treating both the slot's xmin and catalog_xmin similarly
> > with the single GUC.
>
> Thanks for reviewing the patch.
>
> > > >> I made the following design choice: try invalidating only once per
> > > >> vacuum cycle, not per table. While this keeps the cost of checking
> > > >> (incl. the XidGenLock contention) for invalidation to a minimum when
> > > >> there are a large number of tables and replication slots, it can be
> > > >> less effective when individual tables/indexes are large. Invalidating
> > > >> during checkpoints can help to some extent with the large table/index
> > > >> cases. But I'm open to thoughts on this.
> > > >
> > > > It may not solve the intent when the vacuum cycle is longer, which one can expect on a large database particularly when there is heavy bloat.
> > >
> > > This design choice boils down to the following: a database instance
> > > having either 1/ a large number of small tables or 2/ large tables.
> > > From my experience, I have seen both cases but mostly case 2 (others
> > > can correct me). In this context, having an XID age based slot
> > > invalidation check once per relation makes sense. However, I'm open to
> > > more thoughts here.
> >
> > ISTM that checking the XID-based slot invalidation per table would be
> > more bullet-proof and cover many cases. How about checking the
> > XID-based slot invalidation opportunity only when the OldestXmin is
> > older than the new GUC? For example, we can do this check in
> > heap_vacuum_rel() based on the VacuumCutoffs returned by
> > vacuum_get_cutoffs(). If we invalidate at least one slot for its XID,
> > we can re-compute the OldestXmin.
>
> Agreed. Here's the patch that moves the XID-age based slot
> invalidation check to vacuum_get_cutoffs. This has some nice
> advantages: 1/ It makes the check once per table (to help with large
> tables). 2/ It makes the check less costly since we rely on already
> computed OldestXmin and nextXID values. 3/ It avoids the checkpointer
> to do XID-age based slot invalidation which keeps the usage of this
> GUC simple with no additional costs to the checkpointer - just the
> vacuum (both vacuum command and autovacuum) does the invalidation when
> needed.
>
> I moved the new tests to the existing TAP test file
> t/019_replslot_limit.pl alongside other invalidation tests.
>
> I added detailed comments around InvalidateXIDAgedReplicationSlots and
> slightly modified the docs.
>
> Please find the v3 patch for further review.
Thank you for updating the patch. I think the patch is reasonably
simple and can avoid unnecessary overheads well due to XID-based
checks. Here are some comments:
+ /*
+ * Try to invalidate XID-aged replication slots that may interfere with
+ * vacuum's ability to freeze and remove dead tuples. Since OldestXmin
+ * already covers the slot xmin/catalog_xmin values, pass it as a
+ * preliminary check to avoid additional iteration over all the slots.
+ *
+ * If at least one slot was invalidated, recompute OldestXmin so that this
+ * vacuum benefits from the advanced horizon immediately.
+ */
+ if (InvalidateXIDAgedReplicationSlots(cutoffs->OldestXmin, nextXID))
+ {
+ cutoffs->OldestXmin = GetOldestNonRemovableTransactionId(rel);
+ Assert(TransactionIdIsNormal(cutoffs->OldestXmin));
+ }
vacuum_get_cutoff() is also called by VACUUM FULL, CLUSTER, and
REPACK. I'm not sure that users would expect the slot invalidation
also in these commands. I think it's better to leave
vacuum_get_cutoff() a pure cutoff computation function and we can try
to invalidate slots in heap_vacuum_rel(). It requires additional
ReadNextTransactionId() but we can live with it, or we can make
vacuum_get_cutoffs() return the nextXID as well (stored in *cutoffs).
---
+ /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
+ /* this can cause the limit to go backwards by 3, but that's OK */
+ if (!TransactionIdIsNormal(cutoffXID))
+ cutoffXID = FirstNormalTransactionId;
+
+ if (TransactionIdPrecedes(oldestXmin, cutoffXID))
+ {
+ invalidated = InvalidateObsoleteReplicationSlots(RS_INVAL_XID_AGE,
+ 0,
+ InvalidOid,
+ InvalidTransactionId,
+ nextXID);
+ }
I think it's better to check the procArray->replication_slot_xmin and
procArray->replication_slot_catalog_xmin before iterating over each
slot. Otherwise, we would end up checking every slot even when a long
running transaction holds the oldestxmin back.
---
+ if (cutoffXID < FirstNormalTransactionId)
+ cutoffXID -= FirstNormalTransactionId;
and
+ if (!TransactionIdIsNormal(cutoffXID))
+ cutoffXID = FirstNormalTransactionId;
These codes have the same comment but are doing a slightly different
thing. I guess the latter is missing '-'?
Regards,
--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi,
On Tue, Mar 24, 2026 at 11:50 PM Masahiko Sawada wrote:
>
> > Please find the v3 patch for further review.
>
> Thank you for updating the patch. I think the patch is reasonably
> simple and can avoid unnecessary overheads well due to XID-based
> checks. Here are some comments:
Thank you for reviewing the patch.
> vacuum_get_cutoff() is also called by VACUUM FULL, CLUSTER, and
> REPACK. I'm not sure that users would expect the slot invalidation
> also in these commands. I think it's better to leave
> vacuum_get_cutoff() a pure cutoff computation function and we can try
> to invalidate slots in heap_vacuum_rel(). It requires additional
> ReadNextTransactionId() but we can live with it, or we can make
> vacuum_get_cutoffs() return the nextXID as well (stored in *cutoffs).
+1. I chose to perform the slot invalidation in heap_vacuum_rel by
getting the next txn ID and calling vacuum_get_cutoffs again when a
slot gets invalidated. IMHO, this is simple than adding a flag and do
the invalidation selectively in vacuum_get_cutoffs.
> if (TransactionIdPrecedes(oldestXmin, cutoffXID))
> + {
> + invalidated = InvalidateObsoleteReplicationSlots(RS_INVAL_XID_AGE,
> + 0,
> + InvalidOid,
> + InvalidTransactionId,
> + nextXID);
> + }
>
> I think it's better to check the procArray->replication_slot_xmin and
> procArray->replication_slot_catalog_xmin before iterating over each
> slot. Otherwise, we would end up checking every slot even when a long
> running transaction holds the oldestxmin back.
+1. Changed.
> + if (!TransactionIdIsNormal(cutoffXID))
> + cutoffXID = FirstNormalTransactionId;
>
> These codes have the same comment but are doing a slightly different
> thing. I guess the latter is missing '-'?
Fixed the typo.
I fixed a test error being reported in CI.
Please find the attached v4 patch for further review.
I've also attached the 0002 patch that adds a test case to demo a
production-like scenario by pushing the database to XID wraparound
limits and checking if the XID-age based invalidation with the GUC
setting at the default vacuum_failsafe_age of 1.6B works correctly,
and whether autovacuum can successfully remove this replication slot
blocker to proceed with freezing and bring the database back to
normal. I don't intend to get this committed unless others think
otherwise, but I wanted to have this as a reference.
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
SATYANARAYANA NARLAPURAM <satyanarlapuram@gmail.com>
Дата:
On Wed, Mar 25, 2026 at 12:17 PM Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote:
Hi,
On Tue, Mar 24, 2026 at 11:50 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> > Please find the v3 patch for further review.
>
> Thank you for updating the patch. I think the patch is reasonably
> simple and can avoid unnecessary overheads well due to XID-based
> checks. Here are some comments:
Thank you for reviewing the patch.
> vacuum_get_cutoff() is also called by VACUUM FULL, CLUSTER, and
> REPACK. I'm not sure that users would expect the slot invalidation
> also in these commands. I think it's better to leave
> vacuum_get_cutoff() a pure cutoff computation function and we can try
> to invalidate slots in heap_vacuum_rel(). It requires additional
> ReadNextTransactionId() but we can live with it, or we can make
> vacuum_get_cutoffs() return the nextXID as well (stored in *cutoffs).
+1. I chose to perform the slot invalidation in heap_vacuum_rel by
getting the next txn ID and calling vacuum_get_cutoffs again when a
slot gets invalidated. IMHO, this is simple than adding a flag and do
the invalidation selectively in vacuum_get_cutoffs.
> if (TransactionIdPrecedes(oldestXmin, cutoffXID))
> + {
> + invalidated = InvalidateObsoleteReplicationSlots(RS_INVAL_XID_AGE,
> + 0,
> + InvalidOid,
> + InvalidTransactionId,
> + nextXID);
> + }
>
> I think it's better to check the procArray->replication_slot_xmin and
> procArray->replication_slot_catalog_xmin before iterating over each
> slot. Otherwise, we would end up checking every slot even when a long
> running transaction holds the oldestxmin back.
+1. Changed.
> + if (!TransactionIdIsNormal(cutoffXID))
> + cutoffXID = FirstNormalTransactionId;
>
> These codes have the same comment but are doing a slightly different
> thing. I guess the latter is missing '-'?
Fixed the typo.
I fixed a test error being reported in CI.
Please find the attached v4 patch for further review.
InvalidateObsoleteReplicationSlots(uint32 possible_causes,
XLogSegNo oldestSegno, Oid dboid,
- TransactionId snapshotConflictHorizon)
+ TransactionId snapshotConflictHorizon, TransactionId nextXID)
XLogSegNo oldestSegno, Oid dboid,
- TransactionId snapshotConflictHorizon)
+ TransactionId snapshotConflictHorizon, TransactionId nextXID)
May be add TransactionId nextXID in a new line?
Thinking loud, vacuum doesn't run on a hot_standby, that means this GUC is not applicable for hot_standby. Is this intended? Why not call during checkpoint/restorepoint itself like other slot invalidation checks?
Thanks,
Satya
Re: Introduce XID age based replication slot invalidation
От:
SATYANARAYANA NARLAPURAM <satyanarlapuram@gmail.com>
Дата:
Hi,
On Wed, Mar 25, 2026 at 12:17 PM Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote:
Hi,
On Tue, Mar 24, 2026 at 11:50 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> > Please find the v3 patch for further review.
>
> Thank you for updating the patch. I think the patch is reasonably
> simple and can avoid unnecessary overheads well due to XID-based
> checks. Here are some comments:
Thank you for reviewing the patch.
> vacuum_get_cutoff() is also called by VACUUM FULL, CLUSTER, and
> REPACK. I'm not sure that users would expect the slot invalidation
> also in these commands. I think it's better to leave
> vacuum_get_cutoff() a pure cutoff computation function and we can try
> to invalidate slots in heap_vacuum_rel(). It requires additional
> ReadNextTransactionId() but we can live with it, or we can make
> vacuum_get_cutoffs() return the nextXID as well (stored in *cutoffs).
+1. I chose to perform the slot invalidation in heap_vacuum_rel by
getting the next txn ID and calling vacuum_get_cutoffs again when a
slot gets invalidated. IMHO, this is simple than adding a flag and do
the invalidation selectively in vacuum_get_cutoffs.
> if (TransactionIdPrecedes(oldestXmin, cutoffXID))
> + {
> + invalidated = InvalidateObsoleteReplicationSlots(RS_INVAL_XID_AGE,
> + 0,
> + InvalidOid,
> + InvalidTransactionId,
> + nextXID);
> + }
>
> I think it's better to check the procArray->replication_slot_xmin and
> procArray->replication_slot_catalog_xmin before iterating over each
> slot. Otherwise, we would end up checking every slot even when a long
> running transaction holds the oldestxmin back.
+1. Changed.
> + if (!TransactionIdIsNormal(cutoffXID))
> + cutoffXID = FirstNormalTransactionId;
>
> These codes have the same comment but are doing a slightly different
> thing. I guess the latter is missing '-'?
Fixed the typo.
I fixed a test error being reported in CI.
Please find the attached v4 patch for further review.
+ if (InvalidateXIDAgedReplicationSlots(vacrel->cutoffs.OldestXmin,
+ ReadNextTransactionId()))
+ ReadNextTransactionId()))
Does this account catalog xmin for data tables?
Thanks,
Satya
Re: Introduce XID age based replication slot invalidation
On Wed, Mar 25, 2026 at 12:17 PM Bharath Rupireddy
wrote:
>
> Hi,
>
> On Tue, Mar 24, 2026 at 11:50 PM Masahiko Sawada wrote:
> >
> > > Please find the v3 patch for further review.
> >
> > Thank you for updating the patch. I think the patch is reasonably
> > simple and can avoid unnecessary overheads well due to XID-based
> > checks. Here are some comments:
>
> Thank you for reviewing the patch.
>
> > vacuum_get_cutoff() is also called by VACUUM FULL, CLUSTER, and
> > REPACK. I'm not sure that users would expect the slot invalidation
> > also in these commands. I think it's better to leave
> > vacuum_get_cutoff() a pure cutoff computation function and we can try
> > to invalidate slots in heap_vacuum_rel(). It requires additional
> > ReadNextTransactionId() but we can live with it, or we can make
> > vacuum_get_cutoffs() return the nextXID as well (stored in *cutoffs).
>
> +1. I chose to perform the slot invalidation in heap_vacuum_rel by
> getting the next txn ID and calling vacuum_get_cutoffs again when a
> slot gets invalidated. IMHO, this is simple than adding a flag and do
> the invalidation selectively in vacuum_get_cutoffs.
>
> > if (TransactionIdPrecedes(oldestXmin, cutoffXID))
> > + {
> > + invalidated = InvalidateObsoleteReplicationSlots(RS_INVAL_XID_AGE,
> > + 0,
> > + InvalidOid,
> > + InvalidTransactionId,
> > + nextXID);
> > + }
> >
> > I think it's better to check the procArray->replication_slot_xmin and
> > procArray->replication_slot_catalog_xmin before iterating over each
> > slot. Otherwise, we would end up checking every slot even when a long
> > running transaction holds the oldestxmin back.
>
> +1. Changed.
>
> > + if (!TransactionIdIsNormal(cutoffXID))
> > + cutoffXID = FirstNormalTransactionId;
> >
> > These codes have the same comment but are doing a slightly different
> > thing. I guess the latter is missing '-'?
>
> Fixed the typo.
>
> I fixed a test error being reported in CI.
>
> Please find the attached v4 patch for further review.
Thank you for updating the patch. I've reviewed the patch and have
some review comments:
+ /* translator: %s is a GUC variable name */
+ appendStringInfo(&err_detail, _("The slot's xmin
%u at next transaction ID %u exceeds the age %d specified by
\"%s\"."),
+ xmin,
+ nextXID,
+ max_slot_xid_age,
+ "max_slot_xid_age");
I think it's better to show the age of the slot's xmin instead of the
recent XID.
---
+
+ if (!TransactionIdIsNormal(oldestXmin) || !TransactionIdIsNormal(nextXID))
+ return false;
+
Do we expect that the passed oldestXmin or nextXID could be non-normal
XIDs? I think the function assumes these are valid XIDs.
Also, since this function is called only by heap_vacuum_rel(), we can
call ReadNextTransactionId() within this function.
---
+ if (IsReplicationSlotXIDAged(slot_xmin, slot_catalog_xmin, nextXID))
We compute the cutoff XID in IsReplicationSlotXIDAged() again, which
seems redundant.
I've attached the fixup patch addressing these comments and having
some code cleanups. Please review it.
I'm reviewing the regression test part, and will share review comments soon.
>
> I've also attached the 0002 patch that adds a test case to demo a
> production-like scenario by pushing the database to XID wraparound
> limits and checking if the XID-age based invalidation with the GUC
> setting at the default vacuum_failsafe_age of 1.6B works correctly,
> and whether autovacuum can successfully remove this replication slot
> blocker to proceed with freezing and bring the database back to
> normal. I don't intend to get this committed unless others think
> otherwise, but I wanted to have this as a reference.
Thank you for sharing the test script! I'll check it as well.
Regards,
--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi,
On Thu, Mar 26, 2026 at 2:50 PM Masahiko Sawada wrote:
>
> Thank you for updating the patch. I've reviewed the patch and have
> some review comments:
Thank you for reviewing the patch.
> + /* translator: %s is a GUC variable name */
> + appendStringInfo(&err_detail, _("The slot's xmin
> %u at next transaction ID %u exceeds the age %d specified by
> \"%s\"."),
> + xmin,
> + nextXID,
> + max_slot_xid_age,
> + "max_slot_xid_age");
>
> I think it's better to show the age of the slot's xmin instead of the
> recent XID.
Agreed.
> ---
> +
> + if (!TransactionIdIsNormal(oldestXmin) || !TransactionIdIsNormal(nextXID))
> + return false;
> +
>
> Do we expect that the passed oldestXmin or nextXID could be non-normal
> XIDs? I think the function assumes these are valid XIDs.
The oldestXmin is now removed. Please see the responses at the end.
> Also, since this function is called only by heap_vacuum_rel(), we can
> call ReadNextTransactionId() within this function.
Agreed.
> ---
> + if (IsReplicationSlotXIDAged(slot_xmin, slot_catalog_xmin, nextXID))
>
> We compute the cutoff XID in IsReplicationSlotXIDAged() again, which
> seems redundant.
>
> I've attached the fixup patch addressing these comments and having
> some code cleanups. Please review it.
The fixup patch looked good to me, I had that merged in the attached v5 patch.
> I'm reviewing the regression test part, and will share review comments soon.
>
> > I've also attached the 0002 patch that adds a test case to demo a
> > production-like scenario by pushing the database to XID wraparound
> > limits and checking if the XID-age based invalidation with the GUC
> > setting at the default vacuum_failsafe_age of 1.6B works correctly,
> > and whether autovacuum can successfully remove this replication slot
> > blocker to proceed with freezing and bring the database back to
> > normal. I don't intend to get this committed unless others think
> > otherwise, but I wanted to have this as a reference.
>
> Thank you for sharing the test script! I'll check it as well.
Thank you.
On Thu, Mar 26, 2026 at 3:42 AM SATYANARAYANA NARLAPURAM
wrote:
>
> Hi,
>
> + if (InvalidateXIDAgedReplicationSlots(vacrel->cutoffs.OldestXmin,
> + ReadNextTransactionId()))
>
> Does this account catalog xmin for data tables?
Nice catch! When vacuum runs on regular tables, it doesn't cover
catalog_xmin in the OldestXmin. So if catalog_xmin is blocking
relfrozenxid advancement, slot invalidation doesn't happen. I updated
vacuum_get_cutoffs to return slot_catalog_xmin and slot_xmin. These
values are already available in ComputeXidHorizons, so this doesn't
require an additional proc-array lock.
I also added support for XID age based slot invalidation during
checkpoints. This helps standbys that can have replication slots but
where vacuum doesn't run. (It skips synced slots, just like
idle_replication_slot_timeout does.)
Please find the attached v5 patches for further review. Thank you!
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Дата:
Hello,
Thanks for the v5 patch set, I have reviewed and did initial testing on
v5 patch set, and it LGTM, except these
diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c
index 286f0f46341..c2ff7e464f0 100644
--- a/src/backend/replication/slot.c
+++ b/src/backend/replication/slot.c
@@ -1849,7 +1849,7 @@ ReportSlotInvalidation(ReplicationSlotInvalidationCause cause,
else
{
/* translator: %s is a GUC variable name */
- appendStringInfo(&err_detail, _("The slot's xmin %u is %d transactions old, which exceeds the configured \"%s\" value of %d."),
+ appendStringInfo(&err_detail, _("The slot's catalog_xmin %u is %d transactions old, which exceeds the configured \"%s\" value of %d."),
catalog_xmin, (int32) (recentXid - catalog_xmin), "max_slot_xid_age", max_slot_xid_age);
}
while testing the active slot XID age invalidation (SIGTERM path) , i
observed that slot got invalidated , walsender was killed because of
SIGTERM , then starts the infinite-retry-cycle problem where
walreceiver starts walsender and walsender will try to use an invalidated
slot and dies, will think more on this.
Re: Introduce XID age based replication slot invalidation
Hi,
On Sun, Mar 29, 2026 at 1:16 PM Srinath Reddy Sadipiralla
wrote:
>
> Hello,
>
> Thanks for the v5 patch set, I have reviewed and did initial testing on
> v5 patch set, and it LGTM, except these
Thank you for reviewing and testing. I appreciate it.
> diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c
> index 286f0f46341..c2ff7e464f0 100644
> --- a/src/backend/replication/slot.c
> +++ b/src/backend/replication/slot.c
> @@ -1849,7 +1849,7 @@ ReportSlotInvalidation(ReplicationSlotInvalidationCause cause,
> else
> {
> /* translator: %s is a GUC variable name */
> - appendStringInfo(&err_detail, _("The slot's xmin %u is %d transactions old, which exceeds the configured \"%s\" value of %d."),
> + appendStringInfo(&err_detail, _("The slot's catalog_xmin %u is %d transactions old, which exceeds the configured \"%s\" value of %d."),
> catalog_xmin, (int32) (recentXid - catalog_xmin), "max_slot_xid_age", max_slot_xid_age);
> }
Fixed the typo.
> while testing the active slot XID age invalidation (SIGTERM path) , i
> observed that slot got invalidated , walsender was killed because of
> SIGTERM , then starts the infinite-retry-cycle problem where
> walreceiver starts walsender and walsender will try to use an invalidated
> slot and dies, will think more on this.
I would like to clarify that once a slot is invalidated due to any of
the reasons (ReplicationSlotInvalidationCause), it becomes unusable;
the sender will error out if the receiver tries to use it. This is
consistent with all existing slot invalidation mechanisms.
Please find the attached v6 patches fixing the typo for further review.
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Sun, Mar 29, 2026 at 6:35 PM Bharath Rupireddy
wrote:
>
> Hi,
>
> On Sun, Mar 29, 2026 at 1:16 PM Srinath Reddy Sadipiralla
> wrote:
> >
> > Hello,
> >
> > Thanks for the v5 patch set, I have reviewed and did initial testing on
> > v5 patch set, and it LGTM, except these
>
> Thank you for reviewing and testing. I appreciate it.
>
> > diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c
> > index 286f0f46341..c2ff7e464f0 100644
> > --- a/src/backend/replication/slot.c
> > +++ b/src/backend/replication/slot.c
> > @@ -1849,7 +1849,7 @@ ReportSlotInvalidation(ReplicationSlotInvalidationCause cause,
> > else
> > {
> > /* translator: %s is a GUC variable name */
> > - appendStringInfo(&err_detail, _("The slot's xmin %u is %d transactions old, which exceeds the configured \"%s\" value of %d."),
> > + appendStringInfo(&err_detail, _("The slot's catalog_xmin %u is %d transactions old, which exceeds the configured \"%s\" value of %d."),
> > catalog_xmin, (int32) (recentXid - catalog_xmin), "max_slot_xid_age", max_slot_xid_age);
> > }
>
> Fixed the typo.
>
> > while testing the active slot XID age invalidation (SIGTERM path) , i
> > observed that slot got invalidated , walsender was killed because of
> > SIGTERM , then starts the infinite-retry-cycle problem where
> > walreceiver starts walsender and walsender will try to use an invalidated
> > slot and dies, will think more on this.
>
> I would like to clarify that once a slot is invalidated due to any of
> the reasons (ReplicationSlotInvalidationCause), it becomes unusable;
> the sender will error out if the receiver tries to use it. This is
> consistent with all existing slot invalidation mechanisms.
>
> Please find the attached v6 patches fixing the typo for further review.
>
I've reviewed the v6 patch. Here are some comments.
bool
vacuum_get_cutoffs(Relation rel, const VacuumParams params,
- struct VacuumCutoffs *cutoffs)
+ struct VacuumCutoffs *cutoffs,
+ TransactionId *slot_xmin,
+ TransactionId *slot_catalog_xmin)
How about storing both slot_xmin and catalog_xmin into VacuumCutoffs?
---
- if (InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_REMOVED |
RS_INVAL_IDLE_TIMEOUT,
+ possibleInvalidationCauses = RS_INVAL_WAL_REMOVED | RS_INVAL_IDLE_TIMEOUT |
+ RS_INVAL_XID_AGE;
+
+ if (InvalidateObsoleteReplicationSlots(possibleInvalidationCauses,
_logSegNo, InvalidOid,
+ InvalidTransactionId,
+ max_slot_xid_age > 0 ?
+ ReadNextTransactionId() :
InvalidTransactionId))
It's odd to me that we specify RS_INVAL_XID_AGE while passing
InvalidTransactionId. I think we can specify RS_INVAL_XID_AGE along
with a valid recentXId only when we'd like to check the slots based on
their XIDs.
---
+ /* Check if the slot needs to be invalidated due to max_slot_xid_age GUC */
+ if ((possible_causes & RS_INVAL_XID_AGE) && CanInvalidateXidAgedSlot(s))
+ {
+ TransactionId xidLimit;
+
+ Assert(TransactionIdIsValid(recentXid));
+
+ xidLimit = TransactionIdRetreatedBy(recentXid, max_slot_xid_age);
+
I think we can avoid calculating xidLimit for every slot by
calculating it in InvalidatePossiblyObsoleteSlot() and passing it to
DetermineSlotInvalidationCause().
---
*/
TransactionId
GetOldestNonRemovableTransactionId(Relation rel)
+{
+ return GetOldestNonRemovableTransactionIdExt(rel, NULL, NULL);
+}
+
+/*
+ * Same as GetOldestNonRemovableTransactionId(), but also returns the
+ * replication slot xmin and catalog_xmin from the same ComputeXidHorizons()
+ * call. This avoids a separate ProcArrayLock acquisition when the caller
+ * needs both values.
+ */
+TransactionId
+GetOldestNonRemovableTransactionIdExt(Relation rel,
+ TransactionId *slot_xmin,
+ TransactionId *slot_catalog_xmin)
{
I understand that the primary reason why the patch introduces another
variant of GetOldestNonRemovableTransactionId() is to avoid extra
ProcArrayLock acquision to get replication slot xmin and catalog_xmin.
While it's not very elegant, I find that it would not be bad because
otherwise autovacuum takes extra ProcArrayLock (in shared mode) for
every table to vacuum. The ProcArrayLock is already known
high-contented lock it would be better to avoid taking it once more.
If others think differently, we can just call
ProcArrayGetReplicationSlotXmin() separately and compare them to the
limit of XID-age based slot invalidation.
Having said that, I personally don't want to add new instructions to
the existing GetOldestNonRemovableTransactionId(). I guess we might
want to make both the existing function and new function call a common
(inline) function that takes ComputeXidHorizonsResult and returns
appropriate transaction id based on the given relation .
---
+ # Do some work to advance xids
+ $node->safe_psql(
+ 'postgres', qq[
+ do \$\$
+ begin
+ for i in 1..$nxids loop
+ -- use an exception block so that each iteration eats an XID
+ begin
+ insert into $table_name values (i);
+ exception
+ when division_by_zero then null;
+ end;
+ end loop;
+ end\$\$;
+ ]);
I think it's fater to use pg_current_xact_id() instead.
---
+ else
+ {
+ $node->safe_psql('postgres', "VACUUM");
+ }
We don't need to vacuum all tables here.
---
+# Configure primary with XID age settings. Set autovacuum_naptime high so
+# that the checkpointer (not vacuum) triggers the invalidation.
+my $max_slot_xid_age = 500;
+$primary5->append_conf(
+ 'postgresql.conf', qq{
+max_slot_xid_age = $max_slot_xid_age
+autovacuum_naptime = '1h'
+});
I think that it's better to disable autovacuum than setting a large number.
---
+# Testcase end: Invalidate streaming standby's slot due to max_slot_xid_age
+# GUC (via checkpoint).
I think that we can say "physical slot" instead of standby's slot to
avoid confusion as I thought standby's slot is a slot created on the
standby at the first glance.
---
Do we have tests for invalidating slots on the standbys?
Regards,
--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com
RE: Introduce XID age based replication slot invalidation
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Bharath, Thanks for re-working the project. While seeing the old discussion, I found that Robert Haas was agaist the XID-based invalidation, because it's difficult to determine the cutoff age [1]. Can you clarify your thought against the point? Are you focusing on solving the wraparound issues, not for bloated instance issue? The code may not be accepted unless we got his agreement. [1]: https://www.postgresql.org/message-id/CA+TgmoZTbaaEjSZUG1FL0mzxAdN3qmXksO3O9_PZhEuXTkVnRQ@mail.gmail.com Best regards, Hayato Kuroda FUJITSU LIMITED
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Tue, Mar 31, 2026 at 12:25 AM Hayato Kuroda (Fujitsu) wrote: > > Dear Bharath, > > Thanks for re-working the project. Thank you for looking into this. > While seeing the old discussion, I found that Robert Haas was agaist the XID-based > invalidation, because it's difficult to determine the cutoff age [1]. > Can you clarify your thought against the point? Are you focusing on solving the > wraparound issues, not for bloated instance issue? > The code may not be accepted unless we got his agreement. > > [1]: https://www.postgresql.org/message-id/CA+TgmoZTbaaEjSZUG1FL0mzxAdN3qmXksO3O9_PZhEuXTkVnRQ@mail.gmail.com I summarized what others (Nathan, Robert, Amit, Alvaro, Bertrand) said about it here with my responses: https://www.postgresql.org/message-id/CALj2ACVY%2BFd5vC0VjW%3D5VDK9mmt-Y%2BPDZxnBp8ngGAZc24Vv9g%40mail.gmail.com. Please have a look. A good setting for this in production scenarios is to set max_slot_xid_age to vacuum_failsafe_age (1.6B) or little less, so that autovacuum invalidates the slot before entering failsafe mode, unblocking datfrozenxid advancement and avoiding XID wraparound without manual VACUUM or downtime. I added a test for this in the 0002 patch. Please have a look. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi,
On Mon, Mar 30, 2026 at 5:13 PM Masahiko Sawada wrote:
>
> I've reviewed the v6 patch. Here are some comments.
Thank you for reviewing the patch.
> bool
> vacuum_get_cutoffs(Relation rel, const VacuumParams params,
> - struct VacuumCutoffs *cutoffs)
> + struct VacuumCutoffs *cutoffs,
> + TransactionId *slot_xmin,
> + TransactionId *slot_catalog_xmin)
>
> How about storing both slot_xmin and catalog_xmin into VacuumCutoffs?
Done.
> ---
> - if (InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_REMOVED |
> RS_INVAL_IDLE_TIMEOUT,
> + possibleInvalidationCauses = RS_INVAL_WAL_REMOVED | RS_INVAL_IDLE_TIMEOUT |
> + RS_INVAL_XID_AGE;
> +
> + if (InvalidateObsoleteReplicationSlots(possibleInvalidationCauses,
> _logSegNo, InvalidOid,
> + InvalidTransactionId,
> + max_slot_xid_age > 0 ?
> + ReadNextTransactionId() :
> InvalidTransactionId))
>
> It's odd to me that we specify RS_INVAL_XID_AGE while passing
> InvalidTransactionId. I think we can specify RS_INVAL_XID_AGE along
> with a valid recentXId only when we'd like to check the slots based on
> their XIDs.
Done.
> ---
> + /* Check if the slot needs to be invalidated due to max_slot_xid_age GUC */
> + if ((possible_causes & RS_INVAL_XID_AGE) && CanInvalidateXidAgedSlot(s))
> + {
> + TransactionId xidLimit;
> +
> + Assert(TransactionIdIsValid(recentXid));
> +
> + xidLimit = TransactionIdRetreatedBy(recentXid, max_slot_xid_age);
> +
>
> I think we can avoid calculating xidLimit for every slot by
> calculating it in InvalidatePossiblyObsoleteSlot() and passing it to
> DetermineSlotInvalidationCause().
Done.
> ---
> */
> TransactionId
> GetOldestNonRemovableTransactionId(Relation rel)
> +{
> + return GetOldestNonRemovableTransactionIdExt(rel, NULL, NULL);
> +}
> +
> +/*
> + * Same as GetOldestNonRemovableTransactionId(), but also returns the
> + * replication slot xmin and catalog_xmin from the same ComputeXidHorizons()
> + * call. This avoids a separate ProcArrayLock acquisition when the caller
> + * needs both values.
> + */
> +TransactionId
> +GetOldestNonRemovableTransactionIdExt(Relation rel,
> + TransactionId *slot_xmin,
> + TransactionId *slot_catalog_xmin)
> {
>
> I understand that the primary reason why the patch introduces another
> variant of GetOldestNonRemovableTransactionId() is to avoid extra
> ProcArrayLock acquision to get replication slot xmin and catalog_xmin.
> While it's not very elegant, I find that it would not be bad because
> otherwise autovacuum takes extra ProcArrayLock (in shared mode) for
> every table to vacuum. The ProcArrayLock is already known
> high-contented lock it would be better to avoid taking it once more.
> If others think differently, we can just call
> ProcArrayGetReplicationSlotXmin() separately and compare them to the
> limit of XID-age based slot invalidation.
I understand the concerns around the ProcArrayLock and I think a new
function to return the computed slot's xmin and catalog_xmin is good.
> Having said that, I personally don't want to add new instructions to
> the existing GetOldestNonRemovableTransactionId(). I guess we might
> want to make both the existing function and new function call a common
> (inline) function that takes ComputeXidHorizonsResult and returns
> appropriate transaction id based on the given relation .
Done.
> ---
> + # Do some work to advance xids
> + $node->safe_psql(
> + 'postgres', qq[
> + do \$\$
> + begin
> + for i in 1..$nxids loop
> + -- use an exception block so that each iteration eats an XID
> + begin
> + insert into $table_name values (i);
> + exception
> + when division_by_zero then null;
> + end;
> + end loop;
> + end\$\$;
> + ]);
>
> I think it's fater to use pg_current_xact_id() instead.
Done. I pulled this from an existing test case in 001_stream_rep.pl.
Used the pg_current_xact_id approach. Testing times stay the same i.e.
9 wallclock secs.
> ---
> + else
> + {
> + $node->safe_psql('postgres', "VACUUM");
> + }
>
> We don't need to vacuum all tables here.
Fixed.
> ---
> +# Configure primary with XID age settings. Set autovacuum_naptime high so
> +# that the checkpointer (not vacuum) triggers the invalidation.
> +my $max_slot_xid_age = 500;
> +$primary5->append_conf(
> + 'postgresql.conf', qq{
> +max_slot_xid_age = $max_slot_xid_age
> +autovacuum_naptime = '1h'
> +});
>
> I think that it's better to disable autovacuum than setting a large number.
Done.
> ---
> +# Testcase end: Invalidate streaming standby's slot due to max_slot_xid_age
> +# GUC (via checkpoint).
>
> I think that we can say "physical slot" instead of standby's slot to
> avoid confusion as I thought standby's slot is a slot created on the
> standby at the first glance.
Fixed.
> ---
> Do we have tests for invalidating slots on the standbys?
Added a test case for this.
Please find the attached v7 patches for further review. Thank you!
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
On Tue, Mar 31, 2026 at 10:21 AM Bharath Rupireddy
wrote:
>
> Hi,
>
> On Mon, Mar 30, 2026 at 5:13 PM Masahiko Sawada wrote:
> >
> > I've reviewed the v6 patch. Here are some comments.
>
> Thank you for reviewing the patch.
>
> > bool
> > vacuum_get_cutoffs(Relation rel, const VacuumParams params,
> > - struct VacuumCutoffs *cutoffs)
> > + struct VacuumCutoffs *cutoffs,
> > + TransactionId *slot_xmin,
> > + TransactionId *slot_catalog_xmin)
> >
> > How about storing both slot_xmin and catalog_xmin into VacuumCutoffs?
>
> Done.
>
> > ---
> > - if (InvalidateObsoleteReplicationSlots(RS_INVAL_WAL_REMOVED |
> > RS_INVAL_IDLE_TIMEOUT,
> > + possibleInvalidationCauses = RS_INVAL_WAL_REMOVED | RS_INVAL_IDLE_TIMEOUT |
> > + RS_INVAL_XID_AGE;
> > +
> > + if (InvalidateObsoleteReplicationSlots(possibleInvalidationCauses,
> > _logSegNo, InvalidOid,
> > + InvalidTransactionId,
> > + max_slot_xid_age > 0 ?
> > + ReadNextTransactionId() :
> > InvalidTransactionId))
> >
> > It's odd to me that we specify RS_INVAL_XID_AGE while passing
> > InvalidTransactionId. I think we can specify RS_INVAL_XID_AGE along
> > with a valid recentXId only when we'd like to check the slots based on
> > their XIDs.
>
> Done.
>
> > ---
> > + /* Check if the slot needs to be invalidated due to max_slot_xid_age GUC */
> > + if ((possible_causes & RS_INVAL_XID_AGE) && CanInvalidateXidAgedSlot(s))
> > + {
> > + TransactionId xidLimit;
> > +
> > + Assert(TransactionIdIsValid(recentXid));
> > +
> > + xidLimit = TransactionIdRetreatedBy(recentXid, max_slot_xid_age);
> > +
> >
> > I think we can avoid calculating xidLimit for every slot by
> > calculating it in InvalidatePossiblyObsoleteSlot() and passing it to
> > DetermineSlotInvalidationCause().
>
> Done.
>
> > ---
> > */
> > TransactionId
> > GetOldestNonRemovableTransactionId(Relation rel)
> > +{
> > + return GetOldestNonRemovableTransactionIdExt(rel, NULL, NULL);
> > +}
> > +
> > +/*
> > + * Same as GetOldestNonRemovableTransactionId(), but also returns the
> > + * replication slot xmin and catalog_xmin from the same ComputeXidHorizons()
> > + * call. This avoids a separate ProcArrayLock acquisition when the caller
> > + * needs both values.
> > + */
> > +TransactionId
> > +GetOldestNonRemovableTransactionIdExt(Relation rel,
> > + TransactionId *slot_xmin,
> > + TransactionId *slot_catalog_xmin)
> > {
> >
> > I understand that the primary reason why the patch introduces another
> > variant of GetOldestNonRemovableTransactionId() is to avoid extra
> > ProcArrayLock acquision to get replication slot xmin and catalog_xmin.
> > While it's not very elegant, I find that it would not be bad because
> > otherwise autovacuum takes extra ProcArrayLock (in shared mode) for
> > every table to vacuum. The ProcArrayLock is already known
> > high-contented lock it would be better to avoid taking it once more.
> > If others think differently, we can just call
> > ProcArrayGetReplicationSlotXmin() separately and compare them to the
> > limit of XID-age based slot invalidation.
>
> I understand the concerns around the ProcArrayLock and I think a new
> function to return the computed slot's xmin and catalog_xmin is good.
>
> > Having said that, I personally don't want to add new instructions to
> > the existing GetOldestNonRemovableTransactionId(). I guess we might
> > want to make both the existing function and new function call a common
> > (inline) function that takes ComputeXidHorizonsResult and returns
> > appropriate transaction id based on the given relation .
>
> Done.
>
> > ---
> > + # Do some work to advance xids
> > + $node->safe_psql(
> > + 'postgres', qq[
> > + do \$\$
> > + begin
> > + for i in 1..$nxids loop
> > + -- use an exception block so that each iteration eats an XID
> > + begin
> > + insert into $table_name values (i);
> > + exception
> > + when division_by_zero then null;
> > + end;
> > + end loop;
> > + end\$\$;
> > + ]);
> >
> > I think it's fater to use pg_current_xact_id() instead.
>
> Done. I pulled this from an existing test case in 001_stream_rep.pl.
> Used the pg_current_xact_id approach. Testing times stay the same i.e.
> 9 wallclock secs.
>
> > ---
> > + else
> > + {
> > + $node->safe_psql('postgres', "VACUUM");
> > + }
> >
> > We don't need to vacuum all tables here.
>
> Fixed.
>
> > ---
> > +# Configure primary with XID age settings. Set autovacuum_naptime high so
> > +# that the checkpointer (not vacuum) triggers the invalidation.
> > +my $max_slot_xid_age = 500;
> > +$primary5->append_conf(
> > + 'postgresql.conf', qq{
> > +max_slot_xid_age = $max_slot_xid_age
> > +autovacuum_naptime = '1h'
> > +});
> >
> > I think that it's better to disable autovacuum than setting a large number.
>
> Done.
>
> > ---
> > +# Testcase end: Invalidate streaming standby's slot due to max_slot_xid_age
> > +# GUC (via checkpoint).
> >
> > I think that we can say "physical slot" instead of standby's slot to
> > avoid confusion as I thought standby's slot is a slot created on the
> > standby at the first glance.
>
> Fixed.
>
> > ---
> > Do we have tests for invalidating slots on the standbys?
>
> Added a test case for this.
>
> Please find the attached v7 patches for further review. Thank you!
I've reviewed the v7 patch and have some review comments:
+# Advance the given number of XIDs
+sub advance_xids
+{
+ my ($node, $nxids) = @_;
+ my $sql = join(";\n", ("SELECT pg_current_xact_id()") x $nxids);
+ $node->safe_psql('postgres', $sql);
+}
I think we can create a procedure on primary5 instance to consume XIDs
as follow:
$standby5->safe_psql(
'postgres',
qq{CREATE PROCEDURE consume_xid(cnt int)
AS \$\$
DECLARE
i int;
BEGIN
FOR i in 1..cnt LOOP
EXECUTE 'SELECT pg_current_xact_id()';
COMMIT;
END LOOP;
END;
+\$\$
LANGUAGE plpgsql;
});
---
+# Create a subscriber node
+my $subscriber5 = PostgreSQL::Test::Cluster->new('subscriber5');
+$subscriber5->init(allows_streaming => 'logical');
+$subscriber5->start;
Do we really need to create a subscriber for this test? I think we can
simply create a logical slot on the primary5 and test the XID-age
based slot invalidation.
---
I've attached a fixup patch to propose some cleanup and refactoring, including:
- changes to invalidation errdetail message.
- passing xidLimit instead of recentXid to simplify the invalidation logic.
- documentation changes.
- comment changes.
Regards,
--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi,
On Wed, Apr 1, 2026 at 12:39 PM Masahiko Sawada wrote:
>
> I've reviewed the v7 patch and have some review comments:
Thank you for reviewing the patch.
> +# Advance the given number of XIDs
> +sub advance_xids
> +{
> + my ($node, $nxids) = @_;
> + my $sql = join(";\n", ("SELECT pg_current_xact_id()") x $nxids);
> + $node->safe_psql('postgres', $sql);
> +}
>
> I think we can create a procedure on primary5 instance to consume XIDs
> as follow:
>
> $standby5->safe_psql(
> 'postgres',
> qq{CREATE PROCEDURE consume_xid(cnt int)
> AS \$\$
> DECLARE
> i int;
> BEGIN
> FOR i in 1..cnt LOOP
> EXECUTE 'SELECT pg_current_xact_id()';
> COMMIT;
> END LOOP;
> END;
> +\$\$
> LANGUAGE plpgsql;
> });
Agreed. Although the test timings don't improve (9 seconds on my dev
machine) after moving to the procedure vs. sending pg_current_xact_id
SQL statements, the procedure approach looks better and is more
consistent.
> ---
> +# Create a subscriber node
> +my $subscriber5 = PostgreSQL::Test::Cluster->new('subscriber5');
> +$subscriber5->init(allows_streaming => 'logical');
> +$subscriber5->start;
>
> Do we really need to create a subscriber for this test? I think we can
> simply create a logical slot on the primary5 and test the XID-age
> based slot invalidation.
Nice catch! Removed.
> ---
> I've attached a fixup patch to propose some cleanup and refactoring, including:
>
> - changes to invalidation errdetail message.
> - passing xidLimit instead of recentXid to simplify the invalidation logic.
> - documentation changes.
> - comment changes.
I took the above changes into v8 and fixed a typo in using xidLimit
instead of slotXidLimit.
Please find the attached v8 patches for further review. Thank you!
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi, On Wed, Apr 1, 2026 at 2:21 PM Bharath Rupireddy wrote: > > On Wed, Apr 1, 2026 at 12:39 PM Masahiko Sawada wrote: > > > > I've reviewed the v7 patch and have some review comments: > > Thank you for reviewing the patch. > > I took the above changes into v8 and fixed a typo in using xidLimit > instead of slotXidLimit. > > Please find the attached v8 patches for further review. Thank you! Thank you, Sawada-san, for reviewing and providing some offlist comments. 1/ Included a note in the docs to say that logical replication slots are also affected by XID age GUC (similar to idle_replication_slot_timeout). 2/ Added the code to disable the XID age invalidation in pg_createsubscriber similar to timeout invalidation. Commit 72e6c08fea ensured that none of the logical replication slots get invalidated during the upgrade. (I believe the work that pg_upgrade and pg_createsubscriber do is more important, and the slots created and used by them or slots in use during those processes must not interfere with the upgrade or creating a logical replica from a standby.) 3/ Changed the max value of XID age GUC to be equal to that of vacuum failsafe age. In my opinion, the best use of max_slot_xid_age would be to set it equal to or a little less than vacuum_failsafe_age. Also added a note in the docs about this. 4/ Changed variable names for consistency. 5/ Added code to MaybeInvalidateXIDAgedSlots() to skip the slot invalidation attempt (unnecessary work) when slots are not the reason for holding back the OldestXmin. Added an equality check to see if OldestXmin is either OldestSlotXmin or OldestSlotCatalogXmin (all these OldestXXXXmins are computed from the same ComputeXidHorizons() call). This should allow us to skip the slot invalidation attempt when a backend is holding the xmin back (a long-running transaction, for example). Please find the attached v9 patches for further review. Thank you! -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
On Fri, Apr 3, 2026 at 12:05 PM Bharath Rupireddy wrote: > > Hi, > > On Wed, Apr 1, 2026 at 2:21 PM Bharath Rupireddy > wrote: > > > > On Wed, Apr 1, 2026 at 12:39 PM Masahiko Sawada wrote: > > > > > > I've reviewed the v7 patch and have some review comments: > > > > Thank you for reviewing the patch. > > > > I took the above changes into v8 and fixed a typo in using xidLimit > > instead of slotXidLimit. > > > > Please find the attached v8 patches for further review. Thank you! > > Thank you, Sawada-san, for reviewing and providing some offlist comments. > > 1/ Included a note in the docs to say that logical replication slots > are also affected by XID age GUC (similar to > idle_replication_slot_timeout). > > 2/ Added the code to disable the XID age invalidation in > pg_createsubscriber similar to timeout invalidation. Commit 72e6c08fea > ensured that none of the logical replication slots get invalidated > during the upgrade. (I believe the work that pg_upgrade and > pg_createsubscriber do is more important, and the slots created and > used by them or slots in use during those processes must not interfere > with the upgrade or creating a logical replica from a standby.) > > 3/ Changed the max value of XID age GUC to be equal to that of vacuum > failsafe age. In my opinion, the best use of max_slot_xid_age would be > to set it equal to or a little less than vacuum_failsafe_age. Also > added a note in the docs about this. > > 4/ Changed variable names for consistency. > > 5/ Added code to MaybeInvalidateXIDAgedSlots() to skip the slot > invalidation attempt (unnecessary work) when slots are not the reason > for holding back the OldestXmin. Added an equality check to see if > OldestXmin is either OldestSlotXmin or OldestSlotCatalogXmin (all > these OldestXXXXmins are computed from the same ComputeXidHorizons() > call). This should allow us to skip the slot invalidation attempt when > a backend is holding the xmin back (a long-running transaction, for > example). > > Please find the attached v9 patches for further review. Thank you! Thank you for updating the patch! I've made some changes including moving MaybeInvalidateXidAgedSlot() to vacuum.c since the function seems more inherently tied to vacuum context. Also, updated the commit message and fixed typos. Please review the attached patch. Regards, -- Masahiko Sawada Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Sun, Apr 5, 2026 at 1:03 AM Masahiko Sawada wrote: > > Thank you for updating the patch! > > I've made some changes including moving MaybeInvalidateXidAgedSlot() > to vacuum.c since the function seems more inherently tied to vacuum > context. Also, updated the commit message and fixed typos. > > Please review the attached patch. Thank you Sawada-san! I took a look at the v10 patch and it LGTM. I tested it - make check-world passes, pgindent doesn't complain. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Sun, Apr 5, 2026 at 7:52 PM Bharath Rupireddy wrote: > > Hi, > > On Sun, Apr 5, 2026 at 1:03 AM Masahiko Sawada wrote: > > > > Thank you for updating the patch! > > > > I've made some changes including moving MaybeInvalidateXidAgedSlot() > > to vacuum.c since the function seems more inherently tied to vacuum > > context. Also, updated the commit message and fixed typos. > > > > Please review the attached patch. > > Thank you Sawada-san! > > I took a look at the v10 patch and it LGTM. I tested it - make > check-world passes, pgindent doesn't complain. > While reviewing the patch, I found that with this patch, backend processes and autovacuum workers can simultaneously attempt to invalidate the same slot for the same reason. When invalidating a slot, we send a signal to the process owning the slot and wait for it to exit and release the slot. If the process takes a long time to exit for some reason, subsequent autovacuum workers attempting to invalidate the same slot will also send a SIGTERM and get stuck at InvalidatePossiblyObsoleteSlot(). In the worst case, this could result in all autovacuum activity being blocked. I think we need to address this problem. Regards, -- Masahiko Sawada Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Mon, Apr 6, 2026 at 1:45 AM Masahiko Sawada wrote: > > > I took a look at the v10 patch and it LGTM. I tested it - make > > check-world passes, pgindent doesn't complain. > > While reviewing the patch, I found that with this patch, backend > processes and autovacuum workers can simultaneously attempt to > invalidate the same slot for the same reason. When invalidating a > slot, we send a signal to the process owning the slot and wait for it > to exit and release the slot. If the process takes a long time to exit > for some reason, subsequent autovacuum workers attempting to > invalidate the same slot will also send a SIGTERM and get stuck at > InvalidatePossiblyObsoleteSlot(). In the worst case, this could result > in all autovacuum activity being blocked. I think we need to address > this problem. Thank you! You're right that multiple autovacuum workers can wait on the same slot for SIGTERM to take effect on the process (mainly walsenders) holding the slot. Once the process holding the slot exits, one worker finishes the invalidation and the others see it's done and move on. However, IMHO, this is unlikely to be a problem in practice. First, SIGTERM must take a long time to terminate the process holding the slot. This seems unlikely unless I'm missing some cases. Second, the slot's xmin must be very old (past XID age) while the process is still running but slow to exit. If we set max_slot_xid_age close to vacuum_failsafe_age (e.g., 1.6 billion. I've added this note in the docs), it seems unlikely that the replication connection would still be active at that point. Also, concurrent invalidation can already happen today between the startup process and checkpointer on standby. If needed, we could add a flag to skip extra invalidation attempts based on field experience. Since this feature is off by default, I'd prefer to keep things simple, but I'm open to other approaches. Thoughts? -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Дата:
Hi,
On Mon, Apr 6, 2026 at 11:12 PM Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote:
Hi,
On Mon, Apr 6, 2026 at 1:45 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> > I took a look at the v10 patch and it LGTM. I tested it - make
> > check-world passes, pgindent doesn't complain.
>
> While reviewing the patch, I found that with this patch, backend
> processes and autovacuum workers can simultaneously attempt to
> invalidate the same slot for the same reason. When invalidating a
> slot, we send a signal to the process owning the slot and wait for it
> to exit and release the slot. If the process takes a long time to exit
> for some reason, subsequent autovacuum workers attempting to
> invalidate the same slot will also send a SIGTERM and get stuck at
> InvalidatePossiblyObsoleteSlot(). In the worst case, this could result
> in all autovacuum activity being blocked. I think we need to address
> this problem.
Thank you!
You're right that multiple autovacuum workers can wait on the same
slot for SIGTERM to take effect on the process (mainly walsenders)
holding the slot. Once the process holding the slot exits, one worker
finishes the invalidation and the others see it's done and move on.
However, IMHO, this is unlikely to be a problem in practice.
I was able to reproduce this using pg_recvlogical on a slot, by pausing the
walsender using debugger , then i did some hacky stuff around the GUCs
(just to test), but in production IIUC I think During decoding a large transaction
or network delay , the walsender gets stuck for "some" time, so backend and
autovacuum workers get stuck until then, after that they resume their work,
Correct me if I am wrong :)
(just to test), but in production IIUC I think During decoding a large transaction
or network delay , the walsender gets stuck for "some" time, so backend and
autovacuum workers get stuck until then, after that they resume their work,
Correct me if I am wrong :)
If needed, we could add a flag to skip extra invalidation attempts
based on field experience.
+1, yeah this would help other backends or autovacuum workers not
to retry again the same invalidation and stuck , instead they can check
the flag and be assured that slot invalidation is being taken care of,
so others can move on.
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Mon, Apr 6, 2026 at 10:42 AM Bharath Rupireddy wrote: > > On Mon, Apr 6, 2026 at 1:45 AM Masahiko Sawada wrote: > > > > > I took a look at the v10 patch and it LGTM. I tested it - make > > > check-world passes, pgindent doesn't complain. > > > > While reviewing the patch, I found that with this patch, backend > > processes and autovacuum workers can simultaneously attempt to > > invalidate the same slot for the same reason. When invalidating a > > slot, we send a signal to the process owning the slot and wait for it > > to exit and release the slot. If the process takes a long time to exit > > for some reason, subsequent autovacuum workers attempting to > > invalidate the same slot will also send a SIGTERM and get stuck at > > InvalidatePossiblyObsoleteSlot(). In the worst case, this could result > > in all autovacuum activity being blocked. I think we need to address > > this problem. > > Thank you! > > You're right that multiple autovacuum workers can wait on the same > slot for SIGTERM to take effect on the process (mainly walsenders) > holding the slot. Once the process holding the slot exits, one worker > finishes the invalidation and the others see it's done and move on. > > However, IMHO, this is unlikely to be a problem in practice. > > First, SIGTERM must take a long time to terminate the process holding > the slot. This seems unlikely unless I'm missing some cases. > > Second, the slot's xmin must be very old (past XID age) while the > process is still running but slow to exit. If we set max_slot_xid_age > close to vacuum_failsafe_age (e.g., 1.6 billion. I've added this note > in the docs), it seems unlikely that the replication connection would > still be active at that point. > > Also, concurrent invalidation can already happen today between the > startup process and checkpointer on standby. > > If needed, we could add a flag to skip extra invalidation attempts > based on field experience. Since this feature is off by default, I'd > prefer to keep things simple, but I'm open to other approaches. > > Thoughts? Thank you Sawada-san. I've been thinking more about it and I agree we need to address this. While I still think the scenario is unlikely in practice (SIGTERM would have to take a long time, the slot's xmin would have to be very old while the walsender is still running, etc.), I think it's worth handling. I can think of a couple of approaches: 1. Use ConditionVariableTimedSleep instead of ConditionVariableSleep when called from an autovacuum worker. Workers don't block forever, but they still wait for the timeout duration, still send redundant SIGTERMs, and a correct timeout value needs to be chosen. When it expires, the worker either retries (still stuck) or gives up (same as approach 2). 2. Make the vacuum path non-blocking when another process is already invalidating the same slot. The first process to attempt invalidation proceeds normally: it sends SIGTERM and waits on ConditionVariableSleep for the process holding the slot to exit. But if a subsequent autovacuum worker finds that another process has already initiated invalidation of this slot, it skips the slot and proceeds with vacuum instead of waiting on the same ConditionVariableSleep. I think approach 2 is simple. If another process is already invalidating the slot, there's no reason for the autovacuum worker to also block. The tradeoff is that this vacuum cycle's OldestXmin won't move forward and it will need another cycle for this relation. But that's fine given that the scenario as explained above is unlikely to happen in practice. Please let me know if my thinking sounds reasonable. I'm open to other ideas too. Thoughts? -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi, On Wed, Apr 15, 2026 at 10:03 PM Bharath Rupireddy wrote: > > Hi, > > On Mon, Apr 6, 2026 at 10:42 AM Bharath Rupireddy > wrote: > > > > On Mon, Apr 6, 2026 at 1:45 AM Masahiko Sawada wrote: > > > > > > > I took a look at the v10 patch and it LGTM. I tested it - make > > > > check-world passes, pgindent doesn't complain. > > > > > > While reviewing the patch, I found that with this patch, backend > > > processes and autovacuum workers can simultaneously attempt to > > > invalidate the same slot for the same reason. When invalidating a > > > slot, we send a signal to the process owning the slot and wait for it > > > to exit and release the slot. If the process takes a long time to exit > > > for some reason, subsequent autovacuum workers attempting to > > > invalidate the same slot will also send a SIGTERM and get stuck at > > > InvalidatePossiblyObsoleteSlot(). In the worst case, this could result > > > in all autovacuum activity being blocked. I think we need to address > > > this problem. > > > > Thank you! > > > > You're right that multiple autovacuum workers can wait on the same > > slot for SIGTERM to take effect on the process (mainly walsenders) > > holding the slot. Once the process holding the slot exits, one worker > > finishes the invalidation and the others see it's done and move on. > > > > However, IMHO, this is unlikely to be a problem in practice. > > > > First, SIGTERM must take a long time to terminate the process holding > > the slot. This seems unlikely unless I'm missing some cases. > > > > Second, the slot's xmin must be very old (past XID age) while the > > process is still running but slow to exit. If we set max_slot_xid_age > > close to vacuum_failsafe_age (e.g., 1.6 billion. I've added this note > > in the docs), it seems unlikely that the replication connection would > > still be active at that point. > > > > Also, concurrent invalidation can already happen today between the > > startup process and checkpointer on standby. > > > > If needed, we could add a flag to skip extra invalidation attempts > > based on field experience. Since this feature is off by default, I'd > > prefer to keep things simple, but I'm open to other approaches. > > > > Thoughts? > > Thank you Sawada-san. I've been thinking more about it and I agree we > need to address this. While I still think the scenario is unlikely in > practice (SIGTERM would have to take a long time, the slot's xmin > would have to be very old while the walsender is still running, etc.), > I think it's worth handling. > > I can think of a couple of approaches: > > 1. Use ConditionVariableTimedSleep instead of ConditionVariableSleep > when called from an autovacuum worker. Workers don't block forever, > but they still wait for the timeout duration, still send redundant > SIGTERMs, and a correct timeout value needs to be chosen. When it > expires, the worker either retries (still stuck) or gives up (same as > approach 2). > > 2. Make the vacuum path non-blocking when another process is already > invalidating the same slot. The first process to attempt invalidation > proceeds normally: it sends SIGTERM and waits on > ConditionVariableSleep for the process holding the slot to exit. But > if a subsequent autovacuum worker finds that another process has > already initiated invalidation of this slot, it skips the slot and > proceeds with vacuum instead of waiting on the same > ConditionVariableSleep. > > I think approach 2 is simple. If another process is already > invalidating the slot, there's no reason for the autovacuum worker to > also block. The tradeoff is that this vacuum cycle's OldestXmin won't > move forward and it will need another cycle for this relation. But > that's fine given that the scenario as explained above is unlikely to > happen in practice. > > Please let me know if my thinking sounds reasonable. I'm open to other > ideas too. > > Thoughts? I implemented the approach 2 (patch 0003). I added an injection point to mimic the walsender taking time to process SIGTERM, so that the process invalidating the slot waits on the slot's CV. Please have a look and share your thoughts. Thank you! -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Wed, Apr 15, 2026 at 10:03 PM Bharath Rupireddy wrote: > > Hi, > > On Mon, Apr 6, 2026 at 10:42 AM Bharath Rupireddy > wrote: > > > > On Mon, Apr 6, 2026 at 1:45 AM Masahiko Sawada wrote: > > > > > > > I took a look at the v10 patch and it LGTM. I tested it - make > > > > check-world passes, pgindent doesn't complain. > > > > > > While reviewing the patch, I found that with this patch, backend > > > processes and autovacuum workers can simultaneously attempt to > > > invalidate the same slot for the same reason. When invalidating a > > > slot, we send a signal to the process owning the slot and wait for it > > > to exit and release the slot. If the process takes a long time to exit > > > for some reason, subsequent autovacuum workers attempting to > > > invalidate the same slot will also send a SIGTERM and get stuck at > > > InvalidatePossiblyObsoleteSlot(). In the worst case, this could result > > > in all autovacuum activity being blocked. I think we need to address > > > this problem. > > > > Thank you! > > > > You're right that multiple autovacuum workers can wait on the same > > slot for SIGTERM to take effect on the process (mainly walsenders) > > holding the slot. Once the process holding the slot exits, one worker > > finishes the invalidation and the others see it's done and move on. > > > > However, IMHO, this is unlikely to be a problem in practice. > > > > First, SIGTERM must take a long time to terminate the process holding > > the slot. This seems unlikely unless I'm missing some cases. > > > > Second, the slot's xmin must be very old (past XID age) while the > > process is still running but slow to exit. If we set max_slot_xid_age > > close to vacuum_failsafe_age (e.g., 1.6 billion. I've added this note > > in the docs), it seems unlikely that the replication connection would > > still be active at that point. > > > > Also, concurrent invalidation can already happen today between the > > startup process and checkpointer on standby. > > > > If needed, we could add a flag to skip extra invalidation attempts > > based on field experience. Since this feature is off by default, I'd > > prefer to keep things simple, but I'm open to other approaches. > > > > Thoughts? > > Thank you Sawada-san. I've been thinking more about it and I agree we > need to address this. While I still think the scenario is unlikely in > practice (SIGTERM would have to take a long time, the slot's xmin > would have to be very old while the walsender is still running, etc.), > I think it's worth handling. > > I can think of a couple of approaches: > > 1. Use ConditionVariableTimedSleep instead of ConditionVariableSleep > when called from an autovacuum worker. Workers don't block forever, > but they still wait for the timeout duration, still send redundant > SIGTERMs, and a correct timeout value needs to be chosen. When it > expires, the worker either retries (still stuck) or gives up (same as > approach 2). > > 2. Make the vacuum path non-blocking when another process is already > invalidating the same slot. The first process to attempt invalidation > proceeds normally: it sends SIGTERM and waits on > ConditionVariableSleep for the process holding the slot to exit. But > if a subsequent autovacuum worker finds that another process has > already initiated invalidation of this slot, it skips the slot and > proceeds with vacuum instead of waiting on the same > ConditionVariableSleep. > > I think approach 2 is simple. If another process is already > invalidating the slot, there's no reason for the autovacuum worker to > also block. The tradeoff is that this vacuum cycle's OldestXmin won't > move forward and it will need another cycle for this relation. But > that's fine given that the scenario as explained above is unlikely to > happen in practice. > > Please let me know if my thinking sounds reasonable. I'm open to other > ideas too. The third idea I came up with is that (auto)vacuum behaves differently in terms of XID-aged slot invalidation depending on the slot being used or not; (auto)vacuum invalidate the XID-aged slot if no one is holding the slot, and it just wakes up the checkpointer to invalidate the slot if a process is still holding the slot. If the XID-aged slot is not held by any process, (auto)vacuum simply invalidates the slot. I believe that while the former case happens in most cases in practice, delegating the checkpointer to invalidate XID-aged slots might help avoid vacuum from being blocked. What do you think about the above idea? Regards, -- Masahiko Sawada Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Thu, Jul 2, 2026 at 4:18 PM Masahiko Sawada wrote: > > > Thank you Sawada-san. I've been thinking more about it and I agree we > > need to address this. While I still think the scenario is unlikely in > > practice (SIGTERM would have to take a long time, the slot's xmin > > would have to be very old while the walsender is still running, etc.), > > I think it's worth handling. > > > > I can think of a couple of approaches: > > > > 1. Use ConditionVariableTimedSleep instead of ConditionVariableSleep > > when called from an autovacuum worker. Workers don't block forever, > > but they still wait for the timeout duration, still send redundant > > SIGTERMs, and a correct timeout value needs to be chosen. When it > > expires, the worker either retries (still stuck) or gives up (same as > > approach 2). > > > > 2. Make the vacuum path non-blocking when another process is already > > invalidating the same slot. The first process to attempt invalidation > > proceeds normally: it sends SIGTERM and waits on > > ConditionVariableSleep for the process holding the slot to exit. But > > if a subsequent autovacuum worker finds that another process has > > already initiated invalidation of this slot, it skips the slot and > > proceeds with vacuum instead of waiting on the same > > ConditionVariableSleep. > > > > I think approach 2 is simple. If another process is already > > invalidating the slot, there's no reason for the autovacuum worker to > > also block. The tradeoff is that this vacuum cycle's OldestXmin won't > > move forward and it will need another cycle for this relation. But > > that's fine given that the scenario as explained above is unlikely to > > happen in practice. > > > > Please let me know if my thinking sounds reasonable. I'm open to other > > ideas too. > > The third idea I came up with is that (auto)vacuum behaves differently > in terms of XID-aged slot invalidation depending on the slot being > used or not; (auto)vacuum invalidate the XID-aged slot if no one is > holding the slot, and it just wakes up the checkpointer to invalidate > the slot if a process is still holding the slot. If the XID-aged slot > is not held by any process, (auto)vacuum simply invalidates the slot. > I believe that while the former case happens in most cases in > practice, delegating the checkpointer to invalidate XID-aged slots > might help avoid vacuum from being blocked. > > What do you think about the above idea? I see two cases here. 1/ No one is holding the slot. The connection is gone for whatever reason. Here vacuum just acquires and invalidates the slot right away, no signal, no waiting, and this already works. 2/ The slot is held but has aged out, due to a slow connection, replica lag, or slow decoding/apply. This is the case that involves terminating the holder and waiting, which is where blocking can happen. I partially agree with your suggestion for case 2. My preference is to not add any blockers for vacuum. It does opportunistic XID-age invalidation, invalidates the slots it can take without waiting, and leaves the held ones to the checkpointer, which is the guaranteed path. It is also easier to reason about and to explain to users. The tradeoff is that vacuum won't invalidate a held slot in the same pass, so the relation being vacuumed right then doesn't get the advanced horizon. Once the checkpointer has invalidated the slot, later relations pick it up, which may well be in the same vacuum cycle or next. I am fine with that. Given this, I do not think 0003 is needed anymore. Its whole purpose was to stop multiple vacuum processes piling onto the same slot's condition variable. If the vacuum never waits there, that contention cannot happen. There is only one checkpointer. The unheld case is already safe. The check runs under the slot's spinlock, so the first process marks the slot invalidated and any others see it is done and move on. No signal, no waiting. I will drop 0003. I would skip having the vacuum explicitly wake the checkpointer when it sees a held slot. Imagine one walsender holding the slot's xmin and 8 autovacuum workers running. Each worker hits that same held slot and would signal the checkpointer, so we would get a signal per worker for a single slot, repeated every cycle until the checkpointer acts. If the checkpointer is already running, another request gets queued, and this can happen repeatedly, creating a flood of checkpoint requests. Since 0001 already invalidates aged slots during every checkpoint, the slot gets cleaned up on the checkpointer's regular pass anyway. I would rather rely on that than send extra signals to perform checkpoints. Thoughts? -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Jul 6, 2026 at 11:34 PM Bharath Rupireddy wrote: > > Hi, > > On Thu, Jul 2, 2026 at 4:18 PM Masahiko Sawada wrote: > > > > > Thank you Sawada-san. I've been thinking more about it and I agree we > > > need to address this. While I still think the scenario is unlikely in > > > practice (SIGTERM would have to take a long time, the slot's xmin > > > would have to be very old while the walsender is still running, etc.), > > > I think it's worth handling. > > > > > > I can think of a couple of approaches: > > > > > > 1. Use ConditionVariableTimedSleep instead of ConditionVariableSleep > > > when called from an autovacuum worker. Workers don't block forever, > > > but they still wait for the timeout duration, still send redundant > > > SIGTERMs, and a correct timeout value needs to be chosen. When it > > > expires, the worker either retries (still stuck) or gives up (same as > > > approach 2). > > > > > > 2. Make the vacuum path non-blocking when another process is already > > > invalidating the same slot. The first process to attempt invalidation > > > proceeds normally: it sends SIGTERM and waits on > > > ConditionVariableSleep for the process holding the slot to exit. But > > > if a subsequent autovacuum worker finds that another process has > > > already initiated invalidation of this slot, it skips the slot and > > > proceeds with vacuum instead of waiting on the same > > > ConditionVariableSleep. > > > > > > I think approach 2 is simple. If another process is already > > > invalidating the slot, there's no reason for the autovacuum worker to > > > also block. The tradeoff is that this vacuum cycle's OldestXmin won't > > > move forward and it will need another cycle for this relation. But > > > that's fine given that the scenario as explained above is unlikely to > > > happen in practice. > > > > > > Please let me know if my thinking sounds reasonable. I'm open to other > > > ideas too. > > > > The third idea I came up with is that (auto)vacuum behaves differently > > in terms of XID-aged slot invalidation depending on the slot being > > used or not; (auto)vacuum invalidate the XID-aged slot if no one is > > holding the slot, and it just wakes up the checkpointer to invalidate > > the slot if a process is still holding the slot. If the XID-aged slot > > is not held by any process, (auto)vacuum simply invalidates the slot. > > I believe that while the former case happens in most cases in > > practice, delegating the checkpointer to invalidate XID-aged slots > > might help avoid vacuum from being blocked. > > > > What do you think about the above idea? > > I see two cases here. > > 1/ No one is holding the slot. The connection is gone for whatever > reason. Here vacuum just acquires and invalidates the slot right away, > no signal, no waiting, and this already works. > > 2/ The slot is held but has aged out, due to a slow connection, > replica lag, or slow decoding/apply. This is the case that involves > terminating the holder and waiting, which is where blocking can > happen. > > I partially agree with your suggestion for case 2. My preference is to > not add any blockers for vacuum. It does opportunistic XID-age > invalidation, invalidates the slots it can take without waiting, and > leaves the held ones to the checkpointer, which is the guaranteed > path. It is also easier to reason about and to explain to users. > > The tradeoff is that vacuum won't invalidate a held slot in the same > pass, so the relation being vacuumed right then doesn't get the > advanced horizon. Once the checkpointer has invalidated the slot, > later relations pick it up, which may well be in the same vacuum cycle > or next. I am fine with that. > > Given this, I do not think 0003 is needed anymore. Its whole purpose > was to stop multiple vacuum processes piling onto the same slot's > condition variable. If the vacuum never waits there, that contention > cannot happen. There is only one checkpointer. The unheld case is > already safe. The check runs under the slot's spinlock, so the first > process marks the slot invalidated and any others see it is done and > move on. No signal, no waiting. I will drop 0003. Agree to drop 0003 patch. > I would skip having the vacuum explicitly wake the checkpointer when > it sees a held slot. Imagine one walsender holding the slot's xmin and > 8 autovacuum workers running. Each worker hits that same held slot and > would signal the checkpointer, so we would get a signal per worker for > a single slot, repeated every cycle until the checkpointer acts. If > the checkpointer is already running, another request gets queued, and > this can happen repeatedly, creating a flood of checkpoint requests. I agree that we should avoid requesting checkpoints just to invalidate XID-aged slots. > Since 0001 already invalidates aged slots during every checkpoint, the > slot gets cleaned up on the checkpointer's regular pass anyway. I > would rather rely on that than send extra signals to perform > checkpoints. If we rely on the checkpointer for held slot cases, XID-aged slots held by someone could be left for up to one day, the maximum value of checkpoint_timeout, in the worst case. I considered an alternative idea: (auto)vacuum sets a flag on shmem for XID-based slot invalidation and has the checkpointer perform the invalidation upon request, without creating a checkpoint. But that seems beyond the checkpointer's role. Given that it's not common for XID-aged slots to be still held by someone, it would be okay to skip the held slots. The same applies on replicas, where the restartpoint pass is the only mechanism anway. So I agree to simply skip held slots. Regards, -- Masahiko Sawada Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi, On Thu, Jul 9, 2026 at 2:53 PM Masahiko Sawada wrote: > > > I partially agree with your suggestion for case 2. My preference is to > > not add any blockers for vacuum. It does opportunistic XID-age > > invalidation, invalidates the slots it can take without waiting, and > > leaves the held ones to the checkpointer, which is the guaranteed > > path. It is also easier to reason about and to explain to users. > > > The tradeoff is that vacuum won't invalidate a held slot in the same > > pass, so the relation being vacuumed right then doesn't get the > > advanced horizon. Once the checkpointer has invalidated the slot, > > later relations pick it up, which may well be in the same vacuum cycle > > or next. I am fine with that. > > > I would skip having the vacuum explicitly wake the checkpointer when > > it sees a held slot. Imagine one walsender holding the slot's xmin and > > 8 autovacuum workers running. Each worker hits that same held slot and > > would signal the checkpointer, so we would get a signal per worker for > > a single slot, repeated every cycle until the checkpointer acts. If > > the checkpointer is already running, another request gets queued, and > > this can happen repeatedly, creating a flood of checkpoint requests. > > I agree that we should avoid requesting checkpoints just to invalidate > XID-aged slots. > > If we rely on the checkpointer for held slot cases, XID-aged slots > held by someone could be left for up to one day, the maximum value of > checkpoint_timeout, in the worst case. > > Given that it's not common for XID-aged slots to > be still held by someone, it would be okay to skip the held slots. The > same applies on replicas, where the restartpoint pass is the only > mechanism anway. So I agree to simply skip held slots. Thank you! Please find the attached v12 patch with this change. I dropped the 0002 patch that was pushing the tests to reach a production-like XID wraparound since it takes a bit of time to run such tests and I understand that our test infrastructure and resources are not free. I folded the tests into simpler ones in 0001 itself. Tests now cover vacuum, autovacuum invalidating unheld slots, skipping held slots, checkpoint and restartpoint doing the invalidation, and both logical and physical replication slots. I believe this gives good coverage for the feature. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi, On Wed, Aug 12, 2026 at 05:00:00PM -0700, Bharath Rupireddy wrote: > I believe this can happen in practice (as explained above). IMHO, XID > age based slot invalidation must invalidate the synced slot on the > standby Yeah, I agree. Keeping the exemption for idle_replication_slot_timeout but removing it from CanInvalidateXidAgedSlot() makes sense to me. One nuance about 3/ though: the synced slot is current in that case and the stale catalog_xmin is stored on the primary's physical slot. Therefore, the check for aged synced slots would not address this case: the synced slot is not aged, so it would not be invalidated. Worth adding a test with an actual synced slot, including checking that its invalidation releases the feedback horizon on the primary? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
On Thu, Aug 13, 2026 at 5:32 AM Bharath Rupireddy wrote: > > On Tue, Aug 11, 2026 at 7:00 AM Amit Kapila wrote: > > > so is it okay to keep the same behaviour > > for both max_slot_xid_age and idle_replication_slot_timeout w.r.t > > synced slots? I am not sure if this is a real risk or just a > > theoretical possibility but wanted to bring it to your attention so > > that we can consider it. > > I believe this can happen in practice (as explained above). IMHO, XID > age based slot invalidation must invalidate the synced slot on the > standby (just like other invalidations except the idle-timeout based) > if its catalog_xmin is aged and blocking vacuum on the primary. > Fair enough, then let's invalidate synced slots as well on standby due to xid_age but I think it is better to let users build some alerting system before these slots get invalidated. We can add a column similar to wal_status in pg_replication_slots which could help users to indicate that the particular slot is in danger of invalidation. Additionally, for synced slots, we could add a LOG/WARNING when they are nearing invalidation as there are no direct consumers for the same. -- With Regards, Amit Kapila.
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi,
On Mon, Aug 17, 2026 at 10:46 PM Amit Kapila wrote:
>
> > > so is it okay to keep the same behaviour
> > > for both max_slot_xid_age and idle_replication_slot_timeout w.r.t
> > > synced slots? I am not sure if this is a real risk or just a
> > > theoretical possibility but wanted to bring it to your attention so
> > > that we can consider it.
> >
> > I believe this can happen in practice (as explained above). IMHO, XID
> > age based slot invalidation must invalidate the synced slot on the
> > standby (just like other invalidations except the idle-timeout based)
> > if its catalog_xmin is aged and blocking vacuum on the primary.
>
> Fair enough, then let's invalidate synced slots as well on standby due
> to xid_age
Thanks. I will post the new patches soon.
> but I think it is better to let users build some alerting
> system before these slots get invalidated. We can add a column similar
> to wal_status in pg_replication_slots which could help users to
> indicate that the particular slot is in danger of invalidation.
My initial thought is that one can derive such information using the
existing slot's xmin and catalog_xmin columns along with the
max_slot_xid_age GUC value, something like [1], and create alarms if
needed.
XID-age based replication slot invalidation doesn't have intermediate
phases like WAL-based invalidation does, so wal_status makes sense for
WAL-based invalidation but may not be as applicable here.
That said, I'm open to other thoughts on this.
> Additionally, for synced slots, we could add a LOG/WARNING when they
> are nearing invalidation as there are no direct consumers for the
> same.
That's an interesting idea. I see this as useful not just for XID-age
based invalidation but for slot invalidation in general. Having some
warning before a slot gets invalidated, something like when the
database approaches XID wraparound limits, whether built into core or
via a documented SQL query, would be nice to have. It's worth
discussing separately.
[1] For each replication slot, compute the age of whichever xid it
holds back (xmin or catalog_xmin) and show that age as a percentage of
max_slot_xid_age, so one can see how close each slot is to being
invalidated.
SELECT slot_name, slot_type, xmin, catalog_xmin,
greatest(age(xmin), age(catalog_xmin)) AS xid_age,
current_setting('max_slot_xid_age')::bigint AS xid_age_limit,
round(100.0 * greatest(age(xmin), age(catalog_xmin))
/ current_setting('max_slot_xid_age')::numeric, 0) AS pct_of_limit
FROM pg_replication_slots
WHERE current_setting('max_slot_xid_age')::bigint > 0
AND invalidation_reason IS NULL
ORDER BY xid_age DESC NULLS LAST;
slot_name | slot_type | xmin | catalog_xmin | xid_age | xid_age_limit
| pct_of_limit
-----------+-----------+------+--------------+---------+---------------+--------------
slot_1 | logical | | 695 | 900 | 1000
| 90
slot_2 | physical | 795 | | 800 | 1000
| 80
slot_3 | logical | | 1495 | 100 | 1000
| 10
slot_4 | physical | 1595 | | 0 | 1000
| 0
(4 rows)
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi,
On Tue, Aug 25, 2026 at 12:58 AM Bertrand Drouvot
wrote:
>
> Hi,
>
> On Fri, Aug 21, 2026 at 03:05:00PM -0700, Bharath Rupireddy wrote:
> > Please find the attached v14 patches. 0003 now adds support for
> > invalidating XID-aged synced replication slots on standbys.
>
> Thanks for the new version!
>
> I have a few comments:
Thanks for reviewing it and thanks for the off-list conversation.
> === 1
>
> +static inline bool
> +CanInvalidateXidAgedSlot(ReplicationSlot *s)
> +{
> + return (max_slot_xid_age != 0 &&
> + (TransactionIdIsValid(s->data.xmin) ||
> + TransactionIdIsValid(s->data.catalog_xmin)) &&
> + !(RecoveryInProgress() && s->data.synced));
> +}
>
> AFAICS this can also invalidate the reserved pg_conflict_detection slot. The
> checkpoint terminates its logical replication launcher, but the restarted
> launcher reacquires the invalid slot while subscriptions and workers still
> consider conflict information retention active.
>
> I wonder if invalidating this slot should also transition the affected subscriptions
> out of conflict information retention, same as stop_conflict_info_retention() is
> doing?
Since the pg_conflict_detection slot is internally created and
maintained for the user, I don't think invalidating it (by terminating
the launcher and asking every apply worker to stop conflict retention)
is the right approach. After invalidating, the slot cannot be dropped,
and the conflict detection feature will no longer be working
correctly, and the launcher will not error out for invalidated slots.
The user doesn't even have an easy way to deal with this situation.
They would have already set retain_dead_tuples and
max_retention_duration for the subscription, but they now have no way
to get conflict detection to work again.
That said, one of the design goals for the XID-age based slot
invalidation feature is that no slot blocks vacuum indefinitely.
My proposal is to check the age of each worker's
oldest_nonremovable_xid against the XID-age GUC in each apply worker
in should_stop_conflict_info_retention(). If it is aged, stop the
retention. This mechanism is simple to reason about and fits well with
the backoff we already have with max_retention_duration. This keeps
the slot valid but backs off from holding the vacuum.
> Worth adding a test combining retain_dead_tuples with max_slot_xid_age?
Sure, I will add one once we have consensus on the approach.
> === 2
>
> proves that a slot holds OldestXmin, but InvalidateObsoleteReplicationSlots()
> then invalidates every inactive slot older than xid_limit.
>
> For example, suppose slot A is the oldest horizon, a running transaction is next,
> and slot B is newer than that transaction. Both slots exceed max_slot_xid_age.
>
> The function invalidates A and B, although invalidating B cannot advance the
> current vacuum cutoff.
>
> I wonder if vacuum should invalidate only the slot or slots holding the current
> cutoff, recompute it, and repeat, while doing so advances the cutoff?
Just to be clear, logical slots are not invalidated when vacuuming
non-catalog tables. This is detected by checking whether the oldest
xmin computed comes from the slot's catalog_xmin or not (this covers
both shared and non-shared catalogs), to avoid additional non-relevant
work.
Also, vacuum never blocks if the slot is already held (i.e., active)
but XID-aged. This was to avoid vacuum workers waiting.
Invalidating only one slot at a time may not help much. For example,
if slots s1, s2, s3 are all XID-aged, invalidating only s1 means the
next cutoff recomputation finds s2 as the new blocker, and vacuum
won't get much benefit from that cycle. Invalidating all aged slots in
one pass lets vacuum get the full benefit. This keeps the code simple
and the behavior easy to explain, and is consistent with other
invalidation mechanisms we have today.
> === 3
>
> + from pruning dead catalog rows and freezing XIDs. Invalidating such a
> + slot on the standby advances the catalog_xmin held by
> + the primary's physical slot, letting vacuum there proceed.
>
> This does not seem guaranteed with wal_receiver_status_interval = 0.
>
> And I just realized that this is a pre existing behavior: removing a synced slot
> or ordinary logical slot with wal_receiver_status_interval = 0 leaves the old
> catalog_xmin on the primary physical slot.
>
> I wonder if removing or invalidating a logical slot on a standby should request
> immediate hot standby feedback, or if logical slots on standbys should require
> wal_receiver_status_interval > 0 or if we should document the side effects of
> setting it to zero? That's probably worth a dedicated thread though.
I will update the docs to: "Invalidating such a slot on the standby
allows the primary's catalog_xmin to advance once updated HS feedback
is sent. With wal_receiver_status_interval = 0, such feedback is not
sent periodically."
Thoughts?
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Wed, Sep 2, 2026 at 10:32 AM surya poondla wrote: > > Hi Bharath, > >> Please find the attached v14 patches. 0003 now adds support for >> >> invalidating XID-aged synced replication slots on standbys. > > > v14 applies cleanly and builds clean on the master. I think 0003 has a problem when sync_replication_slots is on: the invalidation doesn't stick, > and the slot ends up worse off than before. > > With max_slot_xid_age = 100 on the standby only, and a failover logical slot on the primary with no consumer so its catalog_xmin stays at 695, > consuming 200 XIDs and checkpointing both nodes gives: > > LOG: invalidating obsolete replication slot "failover_slot" > DETAIL: The slot's catalog xmin age of 200 exceeds the configured > "max_slot_xid_age" of 100 by 100 transactions. > LOG: dropped replication slot "failover_slot" of database with OID 5 > LOG: could not synchronize replication slot "failover_slot" [repeats] > > The slot was temporary=false synced=true catalog_xmin=695 beforehand, and ends up temporary=true synced=true invalidation_reason=NULL > catalog_xmin=895. > > The restartpoint invalidates it, then drop_local_obsolete_slots() drops it, since local_sync_slot_required() returns false for a slot "invalidated > while the corresponding remote slot is still valid". synchronize_one_slot() re-creates it as RS_TEMPORARY with a fresh catalog_xmin from GetOldestSafeDecodingTransactionId() (895), and > update_local_synced_slot() then won't sync it, because the remote's catalog_xmin, 695, precedes it. That recovery path works for the existing > invalidation causes because the remote is normally being consumed and soon advances past the standby, but max_slot_xid_age targets slots whose horizon > is not advancing. > > The primary's horizon does get released, the catalog_xmin on the physical slot the standby streams from advanced from 695 to 895. The > cost is the synced slot: it doesn't become sync-ready again, and ReplicationSlotCleanup() drops the worker's temporary slots when it exits, > so it is gone at promotion. invalidation_reason = 'xid_aged' doesn't persist either, so there's nothing left to alert on. > > ReplicationSlotRelease() clears active_proc only for RS_PERSISTENT slots, so the recreated slot stays active (active_pid was > the slotsync worker itself), its frozen catalog_xmin ages out again, and the next restartpoint takes the active branch: > > LOG: terminating process 45192 to release replication slot "failover_slot" > LOG: slot sync worker started > > After which the slot is recreated at catalog_xmin=1095. So roughly every max_slot_xid_age transactions, the checkpointer SIGTERMs the slot sync worker. None of this shows up in Testcase 6, which sets > sync_replication_slots = off and drives the sync by hand, the only configuration in which nothing resurrects the slot. > > Would it make sense to keep the invalidation sticky for this cause, i.e. have local_sync_slot_required() not drop a synced slot invalidated with > RS_INVAL_XID_AGE? The operator would see it, the horizon stays released, and neither the slot nor the worker gets churned. The alternative is Amit's > earlier suggestion of relying on the primary invalidating its own slot, but that doesn't cover your cases 1 and 2. > Thanks for highlighting the case. A few concerns with making the invalidation sticky: - Users are not allowed to drop synced slots on a standby, so we would end up keeping these slots there indefinitely. Recovering from this would then require taking action on the primary, either by dropping the slot there or by toggling failover off and on. - IIUC, the main reason for allowing these slots to be invalidated in the first place is to handle two cases as discussed at [1]: 1) the sync worker being stuck or failing, and 2) sync being disabled with rare or forgotten manual syncs. If the invalidation is sticky, the recovery path for these slots is also blocked. Once the worker recovers or is rerun, synchronize_one_slot() will just keep skipping the slot at the "Skip the sync of an invalidated slot" check (SS_SKIP_INVALID), since nothing else clears a locally invalidated synced slot, so it can never be recreated with fresh state. Also, I think the same stuck state can already be reached when "max_slot_wal_keep_size" is set only on the standby and the remote slot's restart_lsn is not advancing. (I haven't reproduced this though.) The comments above drop_local_obsolete_slots() already anticipate standby-side invalidation from max_slot_wal_keep_size, but assume the slot gets recreated successfully in the next cycle, which doesn't hold when the remote isn't advancing. So IMO max_slot_xid_age is as applicable to invalidating synced slots as max_slot_wal_keep_size already is, and the sync worker's handling of the consequences is the same in both cases. [1] https://www.postgresql.org/message-id/CALj2ACXO6%3D35QSO2CSSCi2qSODCon8VLBZuB3YyXw3bkd1Pk-w%40mail.gmail.com -- Thanks, Nisha
Re: Introduce XID age based replication slot invalidation
От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Nisha,
Thanks for the detailed response.
Thanks for the detailed response.
If the invalidation is sticky, the recovery path for these slots is
also blocked. Once the worker recovers or is rerun,
synchronize_one_slot() will just keep skipping the slot at the "Skip
the sync of an invalidated slot" check (SS_SKIP_INVALID), since
nothing else clears a locally invalidated synced slot, so it can never
be recreated with fresh state.
Agreed, and I'd missed that the drop in drop_local_obsolete_slots() is the only thing that ever clears a locally invalidated synced slot.
Making it sticky would leave the slot skipped at SS_SKIP_INVALID indefinitely, and since ReplicationSlotDrop() refuses synced slots while in recovery there's nothing on the standby either. So please disregard that suggestion.
Making it sticky would leave the slot skipped at SS_SKIP_INVALID indefinitely, and since ReplicationSlotDrop() refuses synced slots while in recovery there's nothing on the standby either. So please disregard that suggestion.
Also, I think the same stuck state can already be reached when
"max_slot_wal_keep_size" is set only on the standby and the remote
slot's restart_lsn is not advancing. (I haven't reproduced this
though.)
I think you're right, and the code path lines up, reserve_wal_for_local_slot() sets the recreated slot's restart_lsn to max(remote restart_lsn, min_safe_lsn), where min_safe_lsn is the lesser of the redo pointer and the minimum slot LSN. After a WAL-based invalidation the recreated slot therefore lands ahead of the remote, and update_local_synced_slot() skips it on the restart_lsn half of the same condition the catalog_xmin case trips.
The comments above drop_local_obsolete_slots() already
anticipate standby-side invalidation from max_slot_wal_keep_size, but
assume the slot gets recreated successfully in the next cycle, which
doesn't hold when the remote isn't advancing.
If the two are equivalent, then that comment looks like the concrete thing worth fixing, since it's the assumption that misleads. A note in the docs that a synced slot can be invalidated on the standby, and that recovering it needs action on the primary, might help too, given users can't drop it themselves.
Also, regarding both GUCs, Once the recreated slot is stuck, its frozen restart_lsn or catalog_xmin eventually trips the limit again, and because ReplicationSlotRelease()
leaves active_proc set on temporary slots, each subsequent invalidation terminates the slot sync worker rather than just marking the slot. If that's considered acceptable, fine by me. I mainly wanted to make sure
it was a known consequence rather than a surprise.
Regards,
Surya Poondla
leaves active_proc set on temporary slots, each subsequent invalidation terminates the slot sync worker rather than just marking the slot. If that's considered acceptable, fine by me. I mainly wanted to make sure
it was a known consequence rather than a surprise.
Regards,
Surya Poondla
Re: Introduce XID age based replication slot invalidation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Wed, Sep 16, 2026 at 4:04 AM surya poondla wrote: > >> >> The comments above drop_local_obsolete_slots() already >> anticipate standby-side invalidation from max_slot_wal_keep_size, but >> assume the slot gets recreated successfully in the next cycle, which >> doesn't hold when the remote isn't advancing. > > > If the two are equivalent, then that comment looks like the concrete thing worth fixing, since it's the assumption that misleads. A note in the docs that a synced slot can be invalidated on the standby, and that recovering it needs action on the primary, might help too, given users can't drop it themselves. > +1. It would be good to update the comments above drop_local_obsolete_slots() to cover the new GUC as well. We already have guidance in the docs for such failure scenarios at [1]. I think it broadly covers this GUC case too, but it can be reviewed for completeness. [1] https://www.postgresql.org/docs/current/logicaldecoding-explanation.html#LOGICALDECODING-REPLICATION-SLOTS-SYNCHRONIZATION -- Thanks, Nisha
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Mon, Aug 31, 2026 at 7:35 AM Nisha Moond wrote: > > > > AFAICS this can also invalidate the reserved pg_conflict_detection slot. The > > > checkpoint terminates its logical replication launcher, but the restarted > > > launcher reacquires the invalid slot while subscriptions and workers still > > > consider conflict information retention active. > > > Since the pg_conflict_detection slot is internally created and > > maintained for the user, I don't think invalidating it (by terminating > > the launcher and asking every apply worker to stop conflict retention) > > is the right approach. After invalidating, the slot cannot be dropped, > > and the conflict detection feature will no longer be working > > correctly, and the launcher will not error out for invalidated slots. > > The user doesn't even have an easy way to deal with this situation. > > They would have already set retain_dead_tuples and > > max_retention_duration for the subscription, but they now have no way > > to get conflict detection to work again. > > > > That said, one of the design goals for the XID-age based slot > > invalidation feature is that no slot blocks vacuum indefinitely. > > > > My proposal is to check the age of each worker's > > oldest_nonremovable_xid against the XID-age GUC in each apply worker > > in should_stop_conflict_info_retention(). If it is aged, stop the > > retention. This mechanism is simple to reason about and fits well with > > the backoff we already have with max_retention_duration. This keeps > > the slot valid but backs off from holding the vacuum. > > The approach looks good to me. > > My concern is that the launcher freezes the slot's xmin based on > policy, independently of the worker's state. Because of this, a > worker-side check cannot really put a limit on how long the xmin can > be held. > > Launcher only advances the slot's xmin when all retention-active > subscriptions are enabled and their workers are running. This is > intentional; otherwise, a disabled subscription could miss conflicts > when it comes back. > > This leads to two cases: > 1) If a subscription is disabled, or its worker has crashed/cannot be > started, there is no worker to call > should_stop_conflict_info_retention(). Nothing else would release the > old xmin. Right. But one can set the retention duration to a really long value and disable subscriptions even today to block the slot's xmin and vacuum. Although we documented this and accepted it as a behavior the user needs to be aware of, in the launcher we don't do anything about it. An idea here could be having the launcher detect such subscriptions with no workers (i.e. disabled), or crashing apply workers, or initial table syncs taking a long time, or workers applying large in-progress transactions, and having its own retention duration check to back off or inform the workers that their retention duration has passed because they didn't show up in a while. I haven't looked at the conflict detection feature discussion thread in depth, but I guess this would have been discussed there. > 2) Even if the worker is running and caught up, its > oldest_nonremovable_xid can be much newer than the slot's frozen > data.xmin. In that case, the worker sees a relatively young XID and > does not back off, while the slot continues to hold the older xmin. That is correct. Because the slot's xmin is the minimum of each worker's oldest xid (oldest_nonremovable_xid) and computed by the launcher, yes that is possible. So I agree with the point below on also driving the xid age check and backoff from the launcher, in addition to each worker. > So, if we exempt the slot and rely on the backoff, then in these cases > the slot stays valid, but max_slot_xid_age stops being a bound on how > long > its xmin is held. > > One idea would be to drive the check from the launcher rather than the > apply worker. It holds the slot, so it can compare the slot's actual > data.xmin > and can act for subscriptions that have no live worker. A worker-side > check would still be worth having on top of that as a refinement, > letting one lagging subscription back off while the others keep > retaining. > > Thoughts? Thanks a lot for the review. I'm still getting familiar with the conflict detection feature, so please let me know if I'm missing anything in the details below. Here are two approaches. One approach is to never invalidate the slot, and to honour max_slot_xid_age by stopping conflict info retention for whoever is holding the slot's xmin back. On the worker side, the existing should_stop_conflict_info_retention() stops retention when the worker's oldest xid has aged past the age limit, whether or not a retention duration is set. On the launcher side, once per cycle, right after it tries to advance the xmin as usual, if the xmin has aged past the age limit it stops retention by setting subretentionactive to false in pg_subscription for the disabled subscriptions, the subscriptions with no apply worker running, and the subscriptions whose apply worker has no valid oldest xid yet or whose oldest xid still equals the slot's xmin. Workers whose oldest xid has moved past the xmin go on retaining. Note that a worker's oldest xid can never be older than the slot's xmin, since it starts at the xmin and only moves forward, so the workers holding the xmin back are exactly the ones whose oldest xid still equals it. Once those subscriptions stop retaining they no longer count towards the xmin, so it advances on the next cycle, or goes invalid if nothing retains any more, and vacuum is unblocked. Resume needs no changes, a stopped subscription comes back the same way it does after a max_retention_duration stop. So the slot's xmin cannot stay past the age limit for more than a launcher cycle or two. An alternative approach is to invalidate the slot and automatically drop it in the launcher. Currently the launcher drops the slot only when no subscription has retain_dead_tuples enabled any more. Apply workers may still be running then, but none of them is maintaining an oldest xid, so dropping there is safe and easy. However, invalidation terminates the launcher since it holds the slot, so the drop and recreate has to happen in the restarted launcher, which comes up holding a slot that is now invalid while the apply workers carry on with retention active and their oldest xids derived from the old slot. The moment the slot is invalidated nothing holds the xmin any more, so vacuum can remove dead tuples the workers still count on, and a recreated slot starts at a newer xmin than the workers' oldest xids. That means the drop and recreate has to be coordinated with the workers, they need to stop and restart so their oldest xids are computed afresh from the new slot, and the retention state in pg_subscription has to be kept in step with the slot's lifecycle across all of this. I prefer the first approach, since it stops retention only for the subscriptions holding the xmin back, they resume on their own once caught up, and the other subscriptions keep detecting conflicts throughout. The second stops conflict detection more broadly and needs coordination with all the apply workers. Thoughts? Thanks for reading this far! -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Fri, Sep 18, 2026 at 10:40:00AM -0700, Bharath Rupireddy wrote: > > One approach is to never invalidate the slot, and to honour > max_slot_xid_age by stopping conflict info retention for whoever is > holding the slot's xmin back. On the worker side, the existing > should_stop_conflict_info_retention() stops retention when the > worker's oldest xid has aged past the age limit, whether or not a > retention duration is set. On the launcher side, once per cycle, right > after it tries to advance the xmin as usual, if the xmin has aged past > the age limit it stops retention by setting subretentionactive to > false in pg_subscription How do you see the launcher updating pg_subscription here? Are you thinking of a launcher specific update path? > I prefer the first approach, +1 on the first approach. It is what I had in mind when suggesting combining the worker and launcher checks. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
Hi, On Fri, Aug 21, 2026 at 3:05 PM Bharath Rupireddy wrote: > > Please find the attached v14 patches. 0003 now adds support for > invalidating XID-aged synced replication slots on standbys. Hi, while the discussion on invalidating the conflict detection slot continues upthread, I made the following changes and attached the v15 patches. I fixed an issue in the 0001 patch where the xid age invalidation used a slot's persisted xmins, while it is the effective ones that hold vacuum back. The patch now uses the effective xmins while deciding whether to invalidate the slot. This covers all the cases where the persisted and effective xmins differ. For example, a slot that is still being created and holds the data xmin to export a snapshot has data.xmin invalid while the effective value is set (added a test case for this in 0001). Another is a logical or synced slot whose catalog_xmin reaches disk before the effective value advances, so the effective one still holds the previous, older xid. On the concurrent repack side, I tested what happens to a repack slot if it gets invalidated midway due to xid age. In this case, the slot is temporary and holds an effective xmin along with the catalog xmin, while its persisted xmin stays invalid. The decoding worker (i.e. owner of the slot) gets signalled and terminated the usual way, and the backend running concurrent repack then gets notified and fails with an error. Since it is a temporary slot, the repack slot also gets dropped when the worker gets terminated, so no leftover slot remains. I didn't add a test for this as it doesn't bring new coverage. Apart from the above, I self-reviewed all the patches and fixed many things. Improved code comments, commit messages, docs, ensured the GUC follows the rules prescribed in 977d865c36, moved the TAP tests into a new file (099_invalidate_xid_aged_slots.pl for now to avoid patch conflicts, will rename it to the next free number before the commit), adjusted them to be simpler, deterministic and to use fewer resources for the same coverage, ensured CI is happy, improved invalidation messages, deduplicated common code, moved the replication slot release in vacuum code after abort transaction, added variable annotations to boolean params in the call sites, added a comment on top of drop_local_obsolete_slots() on how xid-age invalidation can happen for the synced slot on the standby while the primary's slot is valid (review comment raised upthread), ran pgperltidy on TAP tests and many more. Thanks for reading this far. Please have a look at the attached v15 patches. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Wed, Sep 23, 2026 at 11:44 PM Bharath Rupireddy wrote: > > > Thanks for reading this far. Please have a look at the attached v15 patches. > Thanks for the updated patches. - v15-0001 fails to apply on HEAD and needs to be rebased after commit 46024c5. 1) I observed an issue: With v15, an aged failover slot also gets the standby's physical slot invalidated on the primary. This behavior was also mentioned upthread[1]. The standby forwards the synced copy's catalog_xmin through hot_standby_feedback, so the physical slot carries a catalog_xmin ≤ the failover slot's. The primary's checkpoint then invalidates both in the same pass. I reproduced this with max_slot_xid_age = 100 on the primary (0 on the standby) and the failover subscription disabled. The physical slot was invalidated for its catalog xmin age while its xmin age was 0, and the standby now loops on "can no longer access replication slot": slot_name | slot_type | active | xmin | catalog_xmin | xmin_age | cxmin_age | invalidation_reason -----------+-----------+--------+------+--------------+----------+-----------+--------------------- standby_1 | physical | t | 968 | 667 | 0 | 301 | sub1 | logical | f | | 667 | | 301 | CHECKPOINT; standby_1 | physical | f | 968 | 667 | 0 | 301 | xid_aged sub1 | logical | f | | 667 | | 301 | xid_aged With the GUC also set on the standby, 0003 can avoid this only if the standby's restartpoint happens to invalidate the synced copy before the primary's checkpoint runs. IMO, the impact seems high for the cause: - the standby loses streaming and WAL retention, and needs manual action; it may even need a rebuild once the WAL is gone - with the slot in synchronized_standby_slots, other failover slots on the primary would also stall - for synced slots it gains nothing: the failover slot is invalidated anyway, and the next sync would release the catalog_xmin Given the impact, I feel this should be handled. IIUC, the same would also happen for a lagging or abandoned logical slot owned by the standby. The difficulty I see is that the primary sees only one catalog_xmin per physical slot. It can't tell whether the value comes from a synced copy that will resolve itself, or from a lagging or abandoned slot owned by the standby, which shouldn't be allowed to pin the primary's catalog horizon indefinitely. But it may not need to tell. Instead of invalidating the physical slot, the primary could ignore an aged catalog_xmin in the feedback and clear one already stored, so the slot stays valid. Vacuum can then remove those catalog rows, and the standby's existing recovery-conflict handling invalidates the slots that needed them as "rows_removed". Those rows are lost with the current behaviour too, once the physical slot is invalidated; this way the standby just stays connected. The downsides I see: hot_standby_feedback's protection becomes bounded by the primary's max_slot_xid_age, but that's no different from now, where the standby loses its connection at the same bound. Also, the slots on the standby show "rows_removed" as the invalidation reason, though the underlying cause was the catalog_xmin age on the primary. Thoughts? ~~~ 2) One minor comment on 001: +++ b/doc/src/sgml/system-views.sgml ... + xmin or catalog_xmin + has reached the transaction age specified by ... I think we should use "has exceeded" instead of "has reached" for better clarity. [1] https://www.postgresql.org/message-id/CALj2ACWTz5fKMPa0wNghRFdfPBzc%2Bj3x%2BkcXSeCo%2B3twZmDdyg%40mail.gmail.com -- Thanks, Nisha
Re: Introduce XID age based replication slot invalidation
От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Tue, Oct 6, 2026 at 5:18 PM Nisha Moond wrote:
>
> On Wed, Sep 23, 2026 at 11:44 PM Bharath Rupireddy
> wrote:
> >
> >
> > Thanks for reading this far. Please have a look at the attached v15 patches.
> >
>
> Thanks for the updated patches.
> - v15-0001 fails to apply on HEAD and needs to be rebased after commit 46024c5.
>
Found one issue: a long-running transaction on the publisher can get
every healthy logical slot invalidated, without vacuum gaining
anything.
A logical slot's catalog_xmin can't advance past the oldest running
XID (oldestRunningXid in xl_running_xacts, see
SnapBuildProcessRunningXacts()). So a old txn that has an XID pins the
catalog_xmin of all logical slots, even when their subscribers are
active and caught up. Once that txn is older than max_slot_xid_age,
the checkpoint invalidates all of these slots, terminates their
walsenders, and the subscriptions break.
I reproduced this with max_slot_xid_age = 100. I left an open
transaction in one session on the publisher:
postgres=# BEGIN;
postgres=*# SELECT pg_current_xact_id();
pg_current_xact_id
--------------------
674
Then for the test, I created a dead tuple in pg_class (CREATE TABLE
t2; DROP TABLE t2;), which vacuum can't remove because of that
transaction:
postgres=# VACUUM (VERBOSE) pg_class;
tuples: 0 removed, 428 remain, 1 are dead but not yet removable
removable cutoff: 674, which was 3 XIDs old when operation ended
After burning ~150 XIDs to exceed max_slot_xid_age, slot s1 is active
and caught up, but its catalog_xmin is stuck at 674:
slot_name | active | active_pid | catalog_xmin | cxmin_age |
confirmed_flush_lsn | invalidation_reason
-----------+--------+------------+--------------+-----------+---------------------+---------------------
s1 | t | 70432 | 674 | 154 |
0/017E6A90 |
The checkpoint invalidates the slot, but vacuum is still blocked at
the same cutoff:
postgres=# CHECKPOINT;
slot_name | active | catalog_xmin | cxmin_age | confirmed_flush_lsn |
invalidation_reason
-----------+--------+--------------+-----------+---------------------+---------------------
s1 | f | 674 | 154 | 0/017E6A90 | xid_aged
postgres=# VACUUM (VERBOSE) pg_class;
tuples: 0 removed, 428 remain, 1 are dead but not yet removable
removable cutoff: 674, which was 154 XIDs old when operation ended
The dead row is removed only after the long open txn ends, and by then
subscription s1 is already lost.
This is different from wal_removed (max_slot_wal_keep_size). There, a
long running txn that has written WAL can also hold back a slot's
restart_lsn and get it invalidated, but it's the slot, not the txn,
that retains the WAL, so invalidation does free disk space. Here the
txn itself holds the same horizon, so invalidating the slot frees
nothing.
I tested only the checkpoint path, but I think the same applies to the
vacuum path (002) too.
IMO, a slot shouldn't be invalidated for XID age when it isn't what's
holding the horizon back, i.e. invalidate a slot only if its aged
xmin/catalog_xmin precedes the oldest running XID (e.g.
GetOldestActiveTransactionId()).
Thoughts?
--
Thanks,
Nisha
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi,
On Tue, Oct 6, 2026 at 11:31 PM Nisha Moond wrote:
>
> Found one issue: a long-running transaction on the publisher can get
> every healthy logical slot invalidated, without vacuum gaining
> anything.
>
> IMO, a slot shouldn't be invalidated for XID age when it isn't what's
> holding the horizon back, i.e. invalidate a slot only if its aged
> xmin/catalog_xmin precedes the oldest running XID (e.g.
> GetOldestActiveTransactionId()).
>
> Thoughts?
Nice catch! Yes, you are right. Invalidating the slots in this case
seems unnecessary. But I see a problem with using just the oldest
running XID. It doesn't cover a backend that holds only a snapshot
xmin, e.g., a read-only query running for hours, or a repeatable-read
transaction that keeps its snapshot for the whole transaction [1].
Such a backend has no XID, so the oldest running XID doesn't see it,
but it still holds the catalog horizon back.
So I think we need a new function that tells whether a slot is the one
holding the vacuum back right now. It would loop over the proc-array
and do what the xid horizons computation does, but without folding in
the slot xmins, and take a database oid so the checkpointer can ask
for a logical slot's database without being connected to it. This
function gets called only for a slot that has already aged past the
limit, so no proc-array costs in a normal pass over slots. On a
standby, it also covers the primary's transactions from
KnownAssignedXids.
This way, only the slots that really hold the vacuum back get invalidated.
Thoughts?
[1]
-- max_slot_xid_age = 100
-- Session 1, holds a snapshot with no XID assigned
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT 1;
-- Session 2, make some dead rows in pg_class
CREATE TABLE foo(a int);
DROP TABLE foo;
CALL consume_xid(20);
SELECT pg_create_logical_replication_slot('s1', 'test_decoding');
CALL consume_xid(120);
-- Slot gets invalidated but vacuum wont' advance
CHECKPOINT;
SELECT slot_name, catalog_xmin, invalidation_reason FROM pg_replication_slots;
VACUUM (VERBOSE) pg_class;
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Tue, Oct 6, 2026 at 4:49 AM Nisha Moond wrote: > > 1) I observed an issue: > With v15, an aged failover slot also gets the standby's physical slot > invalidated on the primary. This behavior was also mentioned > upthread[1]. > > The standby forwards the synced copy's catalog_xmin through > hot_standby_feedback, so the physical slot carries a catalog_xmin ≤ > the failover slot's. The primary's checkpoint then invalidates both in > the same pass. > > IMO, the impact seems high for the cause: > - the standby loses streaming and WAL retention, and needs manual > action; it may even need a rebuild once the WAL is gone > - with the slot in synchronized_standby_slots, other failover slots > on the primary would also stall > - for synced slots it gains nothing: the failover slot is invalidated > anyway, and the next sync would release the catalog_xmin > Given the impact, I feel this should be handled. Nice catch! I agree with your analysis. > IIUC, the same would also happen for a lagging or abandoned logical > slot owned by the standby. > > The difficulty I see is that the primary sees only one catalog_xmin > per physical slot. It can't tell whether the value comes from a synced > copy that will resolve itself, or from a lagging or abandoned slot > owned by the standby, which shouldn't be allowed to pin the primary's > catalog horizon indefinitely. Yes, AFAICS it happens for both: logical slots doing logical decoding on the standby, and slots being synced from the primary. > But it may not need to tell. Instead of invalidating the physical > slot, the primary could ignore an aged catalog_xmin in the feedback > and clear one already stored, so the slot stays valid. Yes, ignoring the received catalog_xmin from HS feedback seems correct to me. Unless I'm missing something, instead of clearing it the primary can store it up to the limit XID (next XID - XID age), which is newer than the received value. Also, I think we should emit a LOG message when this adjustment is made, for observability. > Vacuum can then > remove those catalog rows, and the standby's existing > recovery-conflict handling invalidates the slots that needed them as > "rows_removed". Those rows are lost with the current behaviour too, > once the physical slot is invalidated; this way the standby just stays > connected. > > The downsides I see: hot_standby_feedback's protection becomes bounded > by the primary's max_slot_xid_age, but that's no different from now, > where the standby loses its connection at the same bound. Also, the > slots on the standby show "rows_removed" as the invalidation reason, > though the underlying cause was the catalog_xmin age on the primary. > > Thoughts? I agree with your approach. With this, a physical slot never gets invalidated for an aged catalog_xmin. The checkpointer also moves the slot's catalog_xmin up to the limit XID when the standby is gone or no HS feedback is received any more. Vacuum then removes the older catalog rows, and the slots on the standby that needed them get invalidated as rows_removed once the standby replays those records. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Tue, Sep 22, 2026 at 2:19 AM Bertrand Drouvot wrote: > > On Fri, Sep 18, 2026 at 10:40:00AM -0700, Bharath Rupireddy wrote: > > > > One approach is to never invalidate the slot, and to honour > > max_slot_xid_age by stopping conflict info retention for whoever is > > holding the slot's xmin back. On the worker side, the existing > > should_stop_conflict_info_retention() stops retention when the > > worker's oldest xid has aged past the age limit, whether or not a > > retention duration is set. On the launcher side, once per cycle, right > > after it tries to advance the xmin as usual, if the xmin has aged past > > the age limit it stops retention by setting subretentionactive to > > false in pg_subscription > > How do you see the launcher updating pg_subscription here? Are you thinking of a > launcher specific update path? > > > I prefer the first approach, > > +1 on the first approach. It is what I had in mind when suggesting combining the > worker and launcher checks. Hm. I realized the launcher doesn’t connect to a specific database. It can read the pg_subscription shared catalog, but it can’t update it, because a catalog update also inserts into the catalog’s indexes, and the index list comes from pg_index, which is database-specific and not accessible there. So I’m thinking of this approach. The launcher checks the slot for XID age, and when the limit is hit it sets a flag in its existing per-subscription shmem (LauncherLastStartTimesEntry) for every subscription still retaining, and lets the apply worker update the catalog. The launcher creates an entry even for the subscriptions whose apply worker is not running, such as disabled ones. When the flag is set, a running apply worker stops through the existing path (stop_conflict_info_retention()), setting subretentionactive to false, and the launcher does not move the slot’s xmin past that worker’s xid until the stop is recorded. For the subscriptions whose apply worker is not running, the launcher stops honoring their retention immediately and their apply worker records the stop when it next starts. Once the xmin is no longer aged, the launcher clears the flag for the subscriptions whose stop is recorded, and retention resumes through the existing path. Until then a worker whose stop is recorded does not resume. This way the slot is never invalidated. For example, with XID age = 100, sub1 enabled and sub2 disabled, both retaining: 1/ The slot's xmin stops advancing at 500, because sub2 has no apply worker. 2/ At XID 600 the xmin is aged, so the launcher flags both. sub1's worker stops retaining and records it. sub2 has no worker, so the launcher stops counting it right away. 3/ Nothing to count, so the launcher clears the slot's xmin and vacuum moves on. The slot stays valid. 4/ The xmin is no longer aged, so the launcher clears sub1's flag. Its worker resumes retaining and the slot's xmin restarts at 600. 5/ sub2 stays flagged. When enabled, its worker records the stop at startup and resumes once it has caught up. Thoughts? -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Introduce XID age based replication slot invalidation
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Wed, Oct 21, 2026 at 01:15:00PM -0700, Bharath Rupireddy wrote: > Hi, > > On Tue, Sep 22, 2026 at 2:19 AM Bertrand Drouvot > wrote: > > > > On Fri, Sep 18, 2026 at 10:40:00AM -0700, Bharath Rupireddy wrote: > > > > > > One approach is to never invalidate the slot, and to honour > > > max_slot_xid_age by stopping conflict info retention for whoever is > > > holding the slot's xmin back. On the worker side, the existing > > > should_stop_conflict_info_retention() stops retention when the > > > worker's oldest xid has aged past the age limit, whether or not a > > > retention duration is set. On the launcher side, once per cycle, right > > > after it tries to advance the xmin as usual, if the xmin has aged past > > > the age limit it stops retention by setting subretentionactive to > > > false in pg_subscription > > > > How do you see the launcher updating pg_subscription here? Are you thinking of a > > launcher specific update path? > > > > > I prefer the first approach, > > > > +1 on the first approach. It is what I had in mind when suggesting combining the > > worker and launcher checks. > > Hm. I realized the launcher doesn’t connect to a specific database. It > can read the pg_subscription shared catalog, but it can’t update it, Yeah, that's the issue I had in mind when asking how the launcher would update pg_subscription. > So I’m thinking of this approach. Overall, the proposed design looks reasonable to me, but I have a couple of questions: > The launcher checks the slot for XID > age, and when the limit is hit it sets a flag in its existing > per-subscription shmem (LauncherLastStartTimesEntry) for every > subscription still retaining, and lets the apply worker update the > catalog. The launcher creates an entry even for the subscriptions > whose apply worker is not running, such as disabled ones. When the > flag is set, a running apply worker stops through the existing path > (stop_conflict_info_retention()), setting subretentionactive to false, > and the launcher does not move the slot’s xmin past that worker’s xid > until the stop is recorded. For the subscriptions whose apply worker > is not running, the launcher stops honoring their retention > immediately and their apply worker records the stop when it next > starts. Could this have the same kind of durability issue as [1]? For a subscription without a running apply worker, the launcher stops honoring retention immediately, but subretentionactive remains true until the worker next starts. What happens if the cleared slot's xmin is persisted and the postmaster restarts in between? > Once the xmin is no longer aged, the launcher clears the flag > for the subscriptions whose stop is recorded, and retention resumes > through the existing path. Until then a worker whose stop is recorded > does not resume. This way the slot is never invalidated. > > For example, with XID age = 100, sub1 enabled and sub2 disabled, both retaining: > > 1/ The slot's xmin stops advancing at 500, because sub2 has no apply worker. > > 2/ At XID 600 the xmin is aged, so the launcher flags both. sub1's > worker stops retaining and records it. sub2 has no worker, so the > launcher stops counting it right away. > > 3/ Nothing to count, so the launcher clears the slot's xmin and vacuum > moves on. The slot stays valid. > > 4/ The xmin is no longer aged, so the launcher clears sub1's flag. Its > worker resumes retaining and the slot's xmin restarts at 600. > > 5/ sub2 stays flagged. When enabled, its worker records the stop at > startup and resumes once it has caught up. > > Thoughts? Isn't this different from what we discussed upthread? IIUC, the idea was to stop retention only for subscriptions whose oldest_nonremovable_xid is keeping the slot's xmin aged, allowing the others to continue normally. For example, if sub1's value has advanced beyond 500, couldn't the launcher stop counting only sub2 and recompute the slot's xmin from sub1's value? [1]: https://postgr.es/m/ao7u5I9OeIR72kGp%40bdtpg Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com