Report oldest xmin source when autovacuum cannot remove tuples
Report oldest xmin source when autovacuum cannot remove tuples
Hi hackers, I am proposing to add the reason for the oldest xmin to VACUUM logs. This feature would be useful for identifying why dead tuples cannot be removed, thereby helping to diagnose and prevent table bloat. The current logs only indicate that dead tuples could not be reclaimed due to the oldest xmin, but they do not reveal the underlying reason. To identify the cause, it is necessary to query multiple views: pg_stat_activity (for active transactions), pg_prepared_xacts (for prepared statements), pg_replication_slots (for replication slots), and pg_stat_replication (for hot standby feedback). However, because the data in these views is volatile, it is difficult to retroactively determine what was holding the oldest xmin at the specific time the log message was generated. This PoC patch addresses this problem. The implementation now outputs the reason for the oldest xmin and, where applicable, the backend PID. This information was originally discarded when calculating the oldest xmin horizon, and the computation required to retrieve these reasons is considered reasonable. The patch is attached. What do you think? -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
HI
Thank you for your path ,This path is extremely helpful.
> +/*
> + * Identifies what determined a relation's OldestXmin horizon.
> + * Used by autovacuum to report why dead tuples were not removable.
> + */
> +typedef enum OldestXminSource
> +{
> + OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION,
> + OLDESTXMIN_SOURCE_HOT_STANDBY_FEEDBACK,
> + OLDESTXMIN_SOURCE_PREPARED_TRANSACTION,
> + OLDESTXMIN_SOURCE_REPLICATION_SLOT,
> + OLDESTXMIN_SOURCE_OTHER
> +} OldestXminSource;
> +
> +typedef struct OldestXminInfo
> +{
> + OldestXminSource source;
> + int backend_pid;
> +} OldestXminInfo;
> + * Identifies what determined a relation's OldestXmin horizon.
> + * Used by autovacuum to report why dead tuples were not removable.
> + */
> +typedef enum OldestXminSource
> +{
> + OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION,
> + OLDESTXMIN_SOURCE_HOT_STANDBY_FEEDBACK,
> + OLDESTXMIN_SOURCE_PREPARED_TRANSACTION,
> + OLDESTXMIN_SOURCE_REPLICATION_SLOT,
> + OLDESTXMIN_SOURCE_OTHER
> +} OldestXminSource;
> +
> +typedef struct OldestXminInfo
> +{
> + OldestXminSource source;
> + int backend_pid;
> +} OldestXminInfo;
I have a question for like this
one session
begin;
select * from table_a
not commit or not closed session
It is in OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION type ?
Thank
On Fri, Oct 31, 2025 at 2:32 PM Shinya Kato <shinya11.kato@gmail.com> wrote:
Hi hackers,
I am proposing to add the reason for the oldest xmin to VACUUM logs.
This feature would be useful for identifying why dead tuples cannot be
removed, thereby helping to diagnose and prevent table bloat.
The current logs only indicate that dead tuples could not be reclaimed
due to the oldest xmin, but they do not reveal the underlying reason.
To identify the cause, it is necessary to query multiple views:
pg_stat_activity (for active transactions), pg_prepared_xacts (for
prepared statements), pg_replication_slots (for replication slots),
and pg_stat_replication (for hot standby feedback). However, because
the data in these views is volatile, it is difficult to retroactively
determine what was holding the oldest xmin at the specific time the
log message was generated.
This PoC patch addresses this problem. The implementation now outputs
the reason for the oldest xmin and, where applicable, the backend PID.
This information was originally discarded when calculating the oldest
xmin horizon, and the computation required to retrieve these reasons
is considered reasonable.
The patch is attached. What do you think?
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
On Fri, Oct 31, 2025 at 5:01 PM wenhui qiu wrote:
>
> HI
> Thank you for your path ,This path is extremely helpful.
Thank you!
> > +/*
> > + * Identifies what determined a relation's OldestXmin horizon.
> > + * Used by autovacuum to report why dead tuples were not removable.
> > + */
> > +typedef enum OldestXminSource
> > +{
> > + OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION,
> > + OLDESTXMIN_SOURCE_HOT_STANDBY_FEEDBACK,
> > + OLDESTXMIN_SOURCE_PREPARED_TRANSACTION,
> > + OLDESTXMIN_SOURCE_REPLICATION_SLOT,
> > + OLDESTXMIN_SOURCE_OTHER
> > +} OldestXminSource;
> > +
> > +typedef struct OldestXminInfo
> > +{
> > + OldestXminSource source;
> > + int backend_pid;
> > +} OldestXminInfo;
> I have a question for like this
> one session
> begin;
> select * from table_a
> not commit or not closed session
> It is in OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION type ?
Exactly. Looking at 010_autovacuum_oldest_xmin_reason.pl should make
it clear which logs are output in which cases. (I just noticed there
seems to be a case where the test fails. I need to fix that.)
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Fri, Oct 31, 2025 at 3:32 PM Shinya Kato wrote:
>
> Hi hackers,
>
> I am proposing to add the reason for the oldest xmin to VACUUM logs.
> This feature would be useful for identifying why dead tuples cannot be
> removed, thereby helping to diagnose and prevent table bloat.
+1
I like this idea. Thanks for working on this!
> This PoC patch addresses this problem. The implementation now outputs
> the reason for the oldest xmin and, where applicable, the backend PID.
> This information was originally discarded when calculating the oldest
> xmin horizon, and the computation required to retrieve these reasons
> is considered reasonable.
>
> The patch is attached. What do you think?
According to cfbot, the 010_autovacuum_oldest_xmin_reason regression test
passes on some platforms but fails on others (see [1]), so it doesn't
appear stable.
When I set up a primary and standby with hot_standby_feedback enabled,
then created an old prepared transaction expected to prevent dead tuples
from being vacuumed, VACUUM VERBOSE reported "hot standby feedback"
instead of "prepared transaction" as the oldest xmin source. This isn't a bug
since both xmins are the same in this case. But it may be confusing?
Would it be better to report "prepared transaction" in such cases?
+ case OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION:
+ msgfmt = include_pid ?
+ _("oldest xmin source: active transaction (pid=%d)\n") :
+ _("oldest xmin source: active transaction\n");
+ break;
+ case OLDESTXMIN_SOURCE_HOT_STANDBY_FEEDBACK:
+ msgfmt = include_pid ?
+ _("oldest xmin source: hot standby feedback (pid=%d)\n") :
+ _("oldest xmin source: hot standby feedback\n");
In these two cases, the PID should always be non-zero, so the message
formats without (pid=%d) might not be necessary.
+ /* Identify what forced each of the horizons above. */
+ OldestXminInfo shared_oldest_nonremovable_info;
+ OldestXminInfo catalog_oldest_nonremovable_info;
+ OldestXminInfo data_oldest_nonremovable_info;
+ OldestXminInfo temp_oldest_nonremovable_info;
It might be good to add a comment explaining why we track
sources only for these four oldest xmins, and not for others
like oldest_considered_running.
+ TransactionId old;
+ TransactionId new_horizon;
+
+ if (!TransactionIdIsValid(candidate))
+ return;
The TransactionIdIsValid(candidate) check may be redundant,
since TransactionIdOlder(old, candidate) already performs
the same validation.
- switch (GlobalVisHorizonKindForRel(rel))
+ kind = GlobalVisHorizonKindForRel(rel);
+ switch (kind)
This change doesn't seem necessary.
Regards,
[1] https://cirrus-ci.com/task/6063548834512896
--
Fujii Masao
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
Hi
Thank you for your response , In this context, that session state is idle in transaction .If we could further distinguish between active sessions that are still running and idle sessions, that would be clearer.
Thanks
On Tue, Nov 4, 2025 at 11:59 PM Fujii Masao <masao.fujii@gmail.com> wrote:
On Fri, Oct 31, 2025 at 3:32 PM Shinya Kato <shinya11.kato@gmail.com> wrote:
>
> Hi hackers,
>
> I am proposing to add the reason for the oldest xmin to VACUUM logs.
> This feature would be useful for identifying why dead tuples cannot be
> removed, thereby helping to diagnose and prevent table bloat.
+1
I like this idea. Thanks for working on this!
> This PoC patch addresses this problem. The implementation now outputs
> the reason for the oldest xmin and, where applicable, the backend PID.
> This information was originally discarded when calculating the oldest
> xmin horizon, and the computation required to retrieve these reasons
> is considered reasonable.
>
> The patch is attached. What do you think?
According to cfbot, the 010_autovacuum_oldest_xmin_reason regression test
passes on some platforms but fails on others (see [1]), so it doesn't
appear stable.
When I set up a primary and standby with hot_standby_feedback enabled,
then created an old prepared transaction expected to prevent dead tuples
from being vacuumed, VACUUM VERBOSE reported "hot standby feedback"
instead of "prepared transaction" as the oldest xmin source. This isn't a bug
since both xmins are the same in this case. But it may be confusing?
Would it be better to report "prepared transaction" in such cases?
+ case OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION:
+ msgfmt = include_pid ?
+ _("oldest xmin source: active transaction (pid=%d)\n") :
+ _("oldest xmin source: active transaction\n");
+ break;
+ case OLDESTXMIN_SOURCE_HOT_STANDBY_FEEDBACK:
+ msgfmt = include_pid ?
+ _("oldest xmin source: hot standby feedback (pid=%d)\n") :
+ _("oldest xmin source: hot standby feedback\n");
In these two cases, the PID should always be non-zero, so the message
formats without (pid=%d) might not be necessary.
+ /* Identify what forced each of the horizons above. */
+ OldestXminInfo shared_oldest_nonremovable_info;
+ OldestXminInfo catalog_oldest_nonremovable_info;
+ OldestXminInfo data_oldest_nonremovable_info;
+ OldestXminInfo temp_oldest_nonremovable_info;
It might be good to add a comment explaining why we track
sources only for these four oldest xmins, and not for others
like oldest_considered_running.
+ TransactionId old;
+ TransactionId new_horizon;
+
+ if (!TransactionIdIsValid(candidate))
+ return;
The TransactionIdIsValid(candidate) check may be redundant,
since TransactionIdOlder(old, candidate) already performs
the same validation.
- switch (GlobalVisHorizonKindForRel(rel))
+ kind = GlobalVisHorizonKindForRel(rel);
+ switch (kind)
This change doesn't seem necessary.
Regards,
[1] https://cirrus-ci.com/task/6063548834512896
--
Fujii Masao
Re: Report oldest xmin source when autovacuum cannot remove tuples
Thanks for starting this thread! This is a very useful
feature that users will find beneficial to easily narrow
down the reason the xmin horizon is being held back,
and take action.
Adding this information to the vacuum logging is useful, but
I can see this information being exposed in a view as well in
the future.
I have a few comments:
A few minor ones:
1/ pid should be declared as "pid_t"
2/ last value of an enum should be have a traling comma
+typedef enum OldestXminSource
+{
+ OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION,
+ OLDESTXMIN_SOURCE_HOT_STANDBY_FEEDBACK,
+ OLDESTXMIN_SOURCE_PREPARED_TRANSACTION,
+ OLDESTXMIN_SOURCE_REPLICATION_SLOT,
+ OLDESTXMIN_SOURCE_OTHER
+} OldestXminSource;
More importantly:
3/ As mentioned earlier in the thread, the "idle-in-transaction"
transactions is not being reported correctly, particularly for write
tansactions. I think that is an important missing case. The reason
for this is the cutoff xmin is not being looked up against the current
list of xid's, so we are not blaming the correct pid.
4/
Thinking about point 3 above, I began to wonder if this
whole thing can be simplified with inspiration. Looking at the
existing BackendXidGetPid(), I think it can.
Based on BackendXidGetPid(), I tried a new routine called
BackendXidFindCutOffReason() which can take in the cutoff xmin,
passed in by vacuum and can walk though the proc array and
determine the reason. We don't need to touch ComputeXidHorizons()
to make this work, it seems to me. This comes with an additional
walk though the procarray holding a shared lock, but I don't think
this will be an issue.
Attached is a rough sketch of BackendXidFindCutOffReason()
For now, I just added NOTICE messages which will log with
VACUUM (verbose) for testing.
This takes what you are doing in v1 inside ComputeXidHorizons()
into a new routine. I think this is a cleaner approach.
5/ Also, I think we should also include tests for serializable
transactions
What do you think?
--
Sami Imseih
Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
Hi Sami
> Thinking about point 3 above, I began to wonder if this
> whole thing can be simplified with inspiration. Looking at the
> existing BackendXidGetPid(), I think it can.
> Based on BackendXidGetPid(), I tried a new routine called
> BackendXidFindCutOffReason() which can take in the cutoff xmin,
> passed in by vacuum and can walk though the proc array and
> determine the reason. We don't need to touch ComputeXidHorizons()
> to make this work, it seems to me. This comes with an additional
> walk though the procarray holding a shared lock, but I don't think
> this will be an issue.
> Attached is a rough sketch of BackendXidFindCutOffReason()
> For now, I just added NOTICE messages which will log with
> VACUUM (verbose) for testing.
> Thinking about point 3 above, I began to wonder if this
> whole thing can be simplified with inspiration. Looking at the
> existing BackendXidGetPid(), I think it can.
> Based on BackendXidGetPid(), I tried a new routine called
> BackendXidFindCutOffReason() which can take in the cutoff xmin,
> passed in by vacuum and can walk though the proc array and
> determine the reason. We don't need to touch ComputeXidHorizons()
> to make this work, it seems to me. This comes with an additional
> walk though the procarray holding a shared lock, but I don't think
> this will be an issue.
> Attached is a rough sketch of BackendXidFindCutOffReason()
> For now, I just added NOTICE messages which will log with
> VACUUM (verbose) for testing.
I like your idea , I think we also could consider introducing a GUC parameter in the future, which would terminate sessions blocking vacuum operations when the table's age reaches vacuum_failsafe_age.
Thanks
On Sat, Nov 15, 2025 at 8:25 AM Sami Imseih <samimseih@gmail.com> wrote:
Thanks for starting this thread! This is a very useful
feature that users will find beneficial to easily narrow
down the reason the xmin horizon is being held back,
and take action.
Adding this information to the vacuum logging is useful, but
I can see this information being exposed in a view as well in
the future.
I have a few comments:
A few minor ones:
1/ pid should be declared as "pid_t"
2/ last value of an enum should be have a traling comma
+typedef enum OldestXminSource
+{
+ OLDESTXMIN_SOURCE_ACTIVE_TRANSACTION,
+ OLDESTXMIN_SOURCE_HOT_STANDBY_FEEDBACK,
+ OLDESTXMIN_SOURCE_PREPARED_TRANSACTION,
+ OLDESTXMIN_SOURCE_REPLICATION_SLOT,
+ OLDESTXMIN_SOURCE_OTHER
+} OldestXminSource;
More importantly:
3/ As mentioned earlier in the thread, the "idle-in-transaction"
transactions is not being reported correctly, particularly for write
tansactions. I think that is an important missing case. The reason
for this is the cutoff xmin is not being looked up against the current
list of xid's, so we are not blaming the correct pid.
4/
Thinking about point 3 above, I began to wonder if this
whole thing can be simplified with inspiration. Looking at the
existing BackendXidGetPid(), I think it can.
Based on BackendXidGetPid(), I tried a new routine called
BackendXidFindCutOffReason() which can take in the cutoff xmin,
passed in by vacuum and can walk though the proc array and
determine the reason. We don't need to touch ComputeXidHorizons()
to make this work, it seems to me. This comes with an additional
walk though the procarray holding a shared lock, but I don't think
this will be an issue.
Attached is a rough sketch of BackendXidFindCutOffReason()
For now, I just added NOTICE messages which will log with
VACUUM (verbose) for testing.
This takes what you are doing in v1 inside ComputeXidHorizons()
into a new routine. I think this is a cleaner approach.
5/ Also, I think we should also include tests for serializable
transactions
What do you think?
--
Sami Imseih
Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Dilip Kumar <dilipbalaut@gmail.com>
Дата:
On Sat, Nov 15, 2025 at 5:56 AM Sami Imseih wrote: > > Thanks for starting this thread! This is a very useful > feature that users will find beneficial to easily narrow > down the reason the xmin horizon is being held back, > and take action. +1 for the idea. In BackendXidFindCutOffReason() you have directly reported using NOTICE I believe that is just to show the idea and you are planning to append this to the main message? Apart from that we are looping the whole pgprocarray, however it is only done when we are vacuuming with verbose mode so might not be that bad. -- Regards, Dilip Kumar Google
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > Thanks for starting this thread! This is a very useful > > feature that users will find beneficial to easily narrow > > down the reason the xmin horizon is being held back, > > and take action. > > +1 for the idea. In BackendXidFindCutOffReason() you have directly > reported using NOTICE I believe that is just to show the idea and you > are planning to append this to the main message? Yes, the NOTICE is just for demonstration. Some more work is needed to integrate the output into the vacuum log. > Apart from that we are looping the whole pgprocarray, however it is > only done when we are vacuuming with verbose mode so might not > be that bad. The extra procarray loop will occur during VACUUM VERBOSE or when a vacuum exceeds log_autovacuum_min_duration, 10 minutes by default. I do think however, we should be more selective when to do this work. We should only care about emitting this information in autovacuum logging if the cutoffs->OldestXmid did not advance between consecutive vacuums. This will mean we we will need to track the last cutoff value in relation stats (pg_stat_user_tables), but I think having this value in stats will be useful on its own actually, as users can use it to track tables with stalled cutoffs even if they don't have sufficient autovacuum logging. What do you think? -- Sami Imseih Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2025-10-31 15:31:40 +0900, Shinya Kato wrote: > The patch is attached. What do you think? The added tests never seem to pass in CI: https://cirrus-ci.com/github/postgresql-cfbot/postgresql/cf%2F6188 Greetings, Andres Freund
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
Thank you all for the review comments, and sorry for the late reply.
I will address the review comments in order.
On Sat, Nov 15, 2025 at 9:25 AM Sami Imseih wrote:
> More importantly:
>
> 3/ As mentioned earlier in the thread, the "idle-in-transaction"
> transactions is not being reported correctly, particularly for write
> tansactions. I think that is an important missing case. The reason
> for this is the cutoff xmin is not being looked up against the current
> list of xid's, so we are not blaming the correct pid.
>
> 4/
> Thinking about point 3 above, I began to wonder if this
> whole thing can be simplified with inspiration. Looking at the
> existing BackendXidGetPid(), I think it can.
>
> Based on BackendXidGetPid(), I tried a new routine called
> BackendXidFindCutOffReason() which can take in the cutoff xmin,
> passed in by vacuum and can walk though the proc array and
> determine the reason. We don't need to touch ComputeXidHorizons()
> to make this work, it seems to me. This comes with an additional
> walk though the procarray holding a shared lock, but I don't think
> this will be an issue.
>
> Attached is a rough sketch of BackendXidFindCutOffReason()
> For now, I just added NOTICE messages which will log with
> VACUUM (verbose) for testing.
Thanks for the revised proposal! Your approach is clear and makes the
code easier to read. However, I’m hesitant to proceed with this idea
for the following reasons:
- The original proposal extends ComputeXidHorizons(), which is always
calculated, so there is almost no additional overhead.
- Your proposal incurs additional cost. Furthermore, the time lag
between the execution of ComputeXidHorizons() and
BackendXidFindCutOffReason() could lead to inaccurate logging.
- I don't believe it is necessary to distinguish between active
transactions and "idle in transaction." These states can change
rapidly, and as long as we have the PID, we can check the current
status via pg_stat_activity.
- Your comment made me realize that it might be appropriate to expose
the oldest xmin in the pg_stat_{all,user,sys}_tables views, rather
than just logging it. In that case, we would need to calculate the
oldest xmin horizon every time. This might be a topic for a separate
thread, but we could consider adding columns such as:
- pg_stat_{all,user,sys}_tables.last_vacuum_oldest_xmin (xid)
- pg_stat_{all,user,sys}_tables.last_vacuum_oldest_xmin_source (text)
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> Thank you all for the review comments, and sorry for the late reply.
> I will address the review comments in order.
>
> On Sat, Nov 15, 2025 at 9:25 AM Sami Imseih wrote:
> > More importantly:
> >
> > 3/ As mentioned earlier in the thread, the "idle-in-transaction"
> > transactions is not being reported correctly, particularly for write
> > tansactions. I think that is an important missing case. The reason
> > for this is the cutoff xmin is not being looked up against the current
> > list of xid's, so we are not blaming the correct pid.
> >
> > 4/
> > Thinking about point 3 above, I began to wonder if this
> > whole thing can be simplified with inspiration. Looking at the
> > existing BackendXidGetPid(), I think it can.
> >
> > Based on BackendXidGetPid(), I tried a new routine called
> > BackendXidFindCutOffReason() which can take in the cutoff xmin,
> > passed in by vacuum and can walk though the proc array and
> > determine the reason. We don't need to touch ComputeXidHorizons()
> > to make this work, it seems to me. This comes with an additional
> > walk though the procarray holding a shared lock, but I don't think
> > this will be an issue.
> >
> > Attached is a rough sketch of BackendXidFindCutOffReason()
> > For now, I just added NOTICE messages which will log with
> > VACUUM (verbose) for testing.
>
> Thanks for the revised proposal! Your approach is clear and makes the
> code easier to read.
My approach is focused on correctness rather than simplicity.
The current logic in ComputeXidHorizons can report the wrong PID for
blocking transactions. For example:
1. start a pgbench with 5 clients for some time ( i.e. 5 minutes )
```
pgbench -i -s50
pgbench -c5 -T300
````
2. start a long running transaction that consumes an XID
```
postgres=# begin;
BEGIN
postgres=*# SELECT txid_current(), pg_backend_pid();
txid_current | pg_backend_pid
--------------+----------------
3665231 | 266601
(1 row)
```
3. run a vacuum
```
postgres=# vacuum verbose pgbench_accounts ;
INFO: vacuuming "postgres.public.pgbench_accounts"
INFO: finished vacuuming "postgres.public.pgbench_accounts": index scans: 0
pages: 0 removed, 59833 remain, 59043 scanned (98.68% of total), 0
eagerly scanned
tuples: 0 removed, 1045578 remain, 35425 are dead but not yet removable
removable cutoff: 4301694, which was 35981 XIDs old when operation ended
oldest xmin source: active transaction (pid=267064)
frozen: 0 pages from table (0.00% of total) had 0 tuples frozen
visibility map: 0 pages set all-visible, 0 pages set all-frozen (0
were all-visible)
index scan bypassed: 405 pages from table (0.68% of total) have 1494
dead item identifiers
avg read rate: 1320.425 MB/s, avg write rate: 2.404 MB/s
buffer usage: 67745 hits, 49974 reads, 91 dirtied
WAL usage: 1 records, 0 full page images, 299 bytes, 0 full page image
bytes, 0 buffers full
system usage: CPU: user: 0.22 s, system: 0.06 s, elapsed: 0.29 s
VACUUM
```
VACUUM reports the oldest-XID source PID as 267090 , but the correct
PID is 267064. This happens because the ComputeXidHorizons loop picks
the first PID it encounters with the cutoff XID, even if other backends
have the same XID. There’s no reliable way within that loop to identify
the actual blocking transaction.
```
postgres=# SELECT pid, datname, usename, state, backend_xmin,
backend_xid, substr(query, 1, 20) as query
FROM pg_stat_activity;
pid | datname | usename | state | backend_xmin |
backend_xid | query
--------+----------+----------+---------------------+--------------+-------------+----------------------
267064 | postgres | postgres | active | 4301694 |
4351291 | UPDATE pgbench_branc
267069 | postgres | postgres | active | 4301694 |
4351332 | UPDATE pgbench_telle
267067 | postgres | postgres | active | 4301694 |
4351299 | UPDATE pgbench_branc
267070 | postgres | postgres | active | 4301694 |
4351279 | UPDATE pgbench_branc
267068 | postgres | postgres | active | |
4351325 | UPDATE pgbench_telle
267066 | postgres | postgres | active | 4301694 |
4351327 | UPDATE pgbench_branc
267065 | postgres | postgres | active | 4301694 |
4351292 | UPDATE pgbench_branc
267077 | postgres | postgres | active | 4301694 |
4351303 | UPDATE pgbench_branc
266606 | postgres | postgres | active | 4301694 |
| SELECT pid, datname,
267071 | postgres | postgres | active | |
| BEGIN;
267072 | postgres | postgres | active | 4301694 |
4351300 | UPDATE pgbench_telle
267073 | postgres | postgres | active | 4301694 |
4351258 | UPDATE pgbench_branc
267075 | postgres | postgres | idle | |
| END;
267074 | postgres | postgres | active | 4301694 |
4351319 | UPDATE pgbench_branc
267076 | postgres | postgres | active | |
4351248 | END;
267084 | postgres | postgres | active | 4301694 |
4351330 | UPDATE pgbench_telle
267078 | postgres | postgres | active | 4301694 |
4351260 | UPDATE pgbench_branc
267082 | postgres | postgres | active | |
4351309 | END;
267081 | postgres | postgres | active | |
4351270 | UPDATE pgbench_branc
267083 | postgres | postgres | active | |
4351313 | END;
267080 | postgres | postgres | active | 4301694 |
4351311 | UPDATE pgbench_branc
267079 | postgres | postgres | active | 4301694 |
4351318 | UPDATE pgbench_branc
267086 | postgres | postgres | active | 4301694 |
4351335 | UPDATE pgbench_branc
267085 | postgres | postgres | active | |
| BEGIN;
267090 | postgres | postgres | idle in transaction | |
4301694 | SELECT txid_current( ************
```
> - Your proposal incurs additional cost. Furthermore, the time lag
> between the execution of ComputeXidHorizons() and
> BackendXidFindCutOffReason() could lead to inaccurate logging.
While scanning the proc array adds some overhead, it could be limited
to cases where multiple VACUUMs are stuck on the same cutoff XID, but
we will need to track the last cutoff-xmin to make that possible.
Alternatively, this information might be better exposed in a new system
view, showing the "PID", "XID," and "reason" a transaction is blocking VACUUM.
This approach is more proactive as a DBA can continuously monitor for
blocking reasons and take action before it becomes an issue.
--
Sami Imseih
Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
Hi Sami
> Alternatively, this information might be better exposed in a new system
> view, showing the "PID", "XID," and "reason" a transaction is blocking VACUUM.
> This approach is more proactive as a DBA can continuously monitor for
> blocking reasons and take action before it becomes an issue.
> view, showing the "PID", "XID," and "reason" a transaction is blocking VACUUM.
> This approach is more proactive as a DBA can continuously monitor for
> blocking reasons and take action before it becomes an issue.
Yes ,If this approach is acceptable, then as a reference for the standby conflict-handling and query replay mechanism, we could consider introducing a GUC parameter to terminate PID that blocks VACUUM freeze when the relation age is approaching the vacuum_failsafe_age threshold.
Thanks
On Tue, Jan 6, 2026 at 6:02 AM Sami Imseih <samimseih@gmail.com> wrote:
> Thank you all for the review comments, and sorry for the late reply.
> I will address the review comments in order.
>
> On Sat, Nov 15, 2025 at 9:25 AM Sami Imseih <samimseih@gmail.com> wrote:
> > More importantly:
> >
> > 3/ As mentioned earlier in the thread, the "idle-in-transaction"
> > transactions is not being reported correctly, particularly for write
> > tansactions. I think that is an important missing case. The reason
> > for this is the cutoff xmin is not being looked up against the current
> > list of xid's, so we are not blaming the correct pid.
> >
> > 4/
> > Thinking about point 3 above, I began to wonder if this
> > whole thing can be simplified with inspiration. Looking at the
> > existing BackendXidGetPid(), I think it can.
> >
> > Based on BackendXidGetPid(), I tried a new routine called
> > BackendXidFindCutOffReason() which can take in the cutoff xmin,
> > passed in by vacuum and can walk though the proc array and
> > determine the reason. We don't need to touch ComputeXidHorizons()
> > to make this work, it seems to me. This comes with an additional
> > walk though the procarray holding a shared lock, but I don't think
> > this will be an issue.
> >
> > Attached is a rough sketch of BackendXidFindCutOffReason()
> > For now, I just added NOTICE messages which will log with
> > VACUUM (verbose) for testing.
>
> Thanks for the revised proposal! Your approach is clear and makes the
> code easier to read.
My approach is focused on correctness rather than simplicity.
The current logic in ComputeXidHorizons can report the wrong PID for
blocking transactions. For example:
1. start a pgbench with 5 clients for some time ( i.e. 5 minutes )
```
pgbench -i -s50
pgbench -c5 -T300
````
2. start a long running transaction that consumes an XID
```
postgres=# begin;
BEGIN
postgres=*# SELECT txid_current(), pg_backend_pid();
txid_current | pg_backend_pid
--------------+----------------
3665231 | 266601
(1 row)
```
3. run a vacuum
```
postgres=# vacuum verbose pgbench_accounts ;
INFO: vacuuming "postgres.public.pgbench_accounts"
INFO: finished vacuuming "postgres.public.pgbench_accounts": index scans: 0
pages: 0 removed, 59833 remain, 59043 scanned (98.68% of total), 0
eagerly scanned
tuples: 0 removed, 1045578 remain, 35425 are dead but not yet removable
removable cutoff: 4301694, which was 35981 XIDs old when operation ended
oldest xmin source: active transaction (pid=267064)
frozen: 0 pages from table (0.00% of total) had 0 tuples frozen
visibility map: 0 pages set all-visible, 0 pages set all-frozen (0
were all-visible)
index scan bypassed: 405 pages from table (0.68% of total) have 1494
dead item identifiers
avg read rate: 1320.425 MB/s, avg write rate: 2.404 MB/s
buffer usage: 67745 hits, 49974 reads, 91 dirtied
WAL usage: 1 records, 0 full page images, 299 bytes, 0 full page image
bytes, 0 buffers full
system usage: CPU: user: 0.22 s, system: 0.06 s, elapsed: 0.29 s
VACUUM
```
VACUUM reports the oldest-XID source PID as 267090 , but the correct
PID is 267064. This happens because the ComputeXidHorizons loop picks
the first PID it encounters with the cutoff XID, even if other backends
have the same XID. There’s no reliable way within that loop to identify
the actual blocking transaction.
```
postgres=# SELECT pid, datname, usename, state, backend_xmin,
backend_xid, substr(query, 1, 20) as query
FROM pg_stat_activity;
pid | datname | usename | state | backend_xmin |
backend_xid | query
--------+----------+----------+---------------------+--------------+-------------+----------------------
267064 | postgres | postgres | active | 4301694 |
4351291 | UPDATE pgbench_branc
267069 | postgres | postgres | active | 4301694 |
4351332 | UPDATE pgbench_telle
267067 | postgres | postgres | active | 4301694 |
4351299 | UPDATE pgbench_branc
267070 | postgres | postgres | active | 4301694 |
4351279 | UPDATE pgbench_branc
267068 | postgres | postgres | active | |
4351325 | UPDATE pgbench_telle
267066 | postgres | postgres | active | 4301694 |
4351327 | UPDATE pgbench_branc
267065 | postgres | postgres | active | 4301694 |
4351292 | UPDATE pgbench_branc
267077 | postgres | postgres | active | 4301694 |
4351303 | UPDATE pgbench_branc
266606 | postgres | postgres | active | 4301694 |
| SELECT pid, datname,
267071 | postgres | postgres | active | |
| BEGIN;
267072 | postgres | postgres | active | 4301694 |
4351300 | UPDATE pgbench_telle
267073 | postgres | postgres | active | 4301694 |
4351258 | UPDATE pgbench_branc
267075 | postgres | postgres | idle | |
| END;
267074 | postgres | postgres | active | 4301694 |
4351319 | UPDATE pgbench_branc
267076 | postgres | postgres | active | |
4351248 | END;
267084 | postgres | postgres | active | 4301694 |
4351330 | UPDATE pgbench_telle
267078 | postgres | postgres | active | 4301694 |
4351260 | UPDATE pgbench_branc
267082 | postgres | postgres | active | |
4351309 | END;
267081 | postgres | postgres | active | |
4351270 | UPDATE pgbench_branc
267083 | postgres | postgres | active | |
4351313 | END;
267080 | postgres | postgres | active | 4301694 |
4351311 | UPDATE pgbench_branc
267079 | postgres | postgres | active | 4301694 |
4351318 | UPDATE pgbench_branc
267086 | postgres | postgres | active | 4301694 |
4351335 | UPDATE pgbench_branc
267085 | postgres | postgres | active | |
| BEGIN;
267090 | postgres | postgres | idle in transaction | |
4301694 | SELECT txid_current( ************
```
> - Your proposal incurs additional cost. Furthermore, the time lag
> between the execution of ComputeXidHorizons() and
> BackendXidFindCutOffReason() could lead to inaccurate logging.
While scanning the proc array adds some overhead, it could be limited
to cases where multiple VACUUMs are stuck on the same cutoff XID, but
we will need to track the last cutoff-xmin to make that possible.
Alternatively, this information might be better exposed in a new system
view, showing the "PID", "XID," and "reason" a transaction is blocking VACUUM.
This approach is more proactive as a DBA can continuously monitor for
blocking reasons and take action before it becomes an issue.
--
Sami Imseih
Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
HI, Sorry for the late reply. I've updated the patch to follow Sami's recommended approach. Overview: - Instead of modifying ComputeXidHorizons(), this patch introduces two new functions: GetXidHorizonBlockers() and GetXidHorizonBlocker(). - GetXidHorizonBlockers() retrieves all potential blockers. This API design leaves open the possibility of exposing this information through a dynamic statistics view in the future [0]. - GetXidHorizonBlocker() selects the highest-priority blocker from the candidates returned by GetXidHorizonBlockers(). - Priority is defined in the XidHorizonBlockerType enum. By distinguishing whether the blocker matches the horizon via xid or xmin, the appropriate blocker is selected. Changes addressed from review comments: - Fixed unstable regression test (Fujii-san's and Andres's comments). - When multiple blockers share the same horizon, the blocker with the highest priority is now selected for output (Fujii-san's comment). - Removed unnecessary code (Fujii-san's comment). - Distinguished between active transactions and idle-in-transaction sessions, and added tests for both (Sami's and Wenhui's comments). - Added a trailing comma to the last value of the enum (Sami's comment). - Added a new function GetXidHorizonBlockers(), modeled after BackendXidGetPid(), instead of modifying ComputeXidHorizons() (Sami's comment). - Added a test for a SERIALIZABLE transaction (Sami's comment). Not addressed: - Did not switch from int to pid_t for the pid type, because int is used consistently throughout the PostgreSQL codebase for this purpose (Sami's comment). Other changes: - Changed the TAP test to use VACUUM (VERBOSE) instead of autovacuum. [0] https://www.postgresql.org/message-id/CAAaqYe9Dy9sicKg3xzCQUMK3VLdEP39g9nMGZheqtFYfNiO5Bg%40mail.gmail.com -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
HI Shinya
ACTIVE_TRANSACTION
IDLE_IN_TRANSACTION
PREPARED_TRANSACTION
Prepared transactions are currently ranked after idle-in-transaction sessions. Operationally, prepared transactions are often harder for DBAs to resolve than idle sessions, so it might be worth clarifying the rationale behind this ordering or reconsidering whether prepared transactions should have higher priority.
> typedef enum XidHorizonBlockerType
> {
> XHB_NONE = 0,
> XHB_ACTIVE_TRANSACTION,
> XHB_IDLE_IN_TRANSACTION,
> XHB_PREPARED_TRANSACTION,
> XHB_XMIN_ACTIVE_TRANSACTION,
> XHB_XMIN_IDLE_IN_TRANSACTION,
> XHB_HOT_STANDBY_FEEDBACK,
> XHB_REPLICATION_SLOT,
> }
> {
> XHB_NONE = 0,
> XHB_ACTIVE_TRANSACTION,
> XHB_IDLE_IN_TRANSACTION,
> XHB_PREPARED_TRANSACTION,
> XHB_XMIN_ACTIVE_TRANSACTION,
> XHB_XMIN_IDLE_IN_TRANSACTION,
> XHB_HOT_STANDBY_FEEDBACK,
> XHB_REPLICATION_SLOT,
> }
Thank you for your working on this ,I have another small suggestion
The priority ordering encoded in XidHorizonBlockerType determines which blocker gets reported when multiple candidates exist. In particular:
ACTIVE_TRANSACTION
IDLE_IN_TRANSACTION
PREPARED_TRANSACTION
Prepared transactions are currently ranked after idle-in-transaction sessions. Operationally, prepared transactions are often harder for DBAs to resolve than idle sessions, so it might be worth clarifying the rationale behind this ordering or reconsidering whether prepared transactions should have higher priority.
> typedef enum XidHorizonBlockerType
> {
> XHB_NONE = 0,
> XHB_ACTIVE_TRANSACTION,
> XHB_PREPARED_TRANSACTION,
> XHB_IDLE_IN_TRANSACTION,
> XHB_XMIN_ACTIVE_TRANSACTION,
> XHB_XMIN_IDLE_IN_TRANSACTION,
> XHB_HOT_STANDBY_FEEDBACK,
> XHB_REPLICATION_SLOT,
> }
> {
> XHB_NONE = 0,
> XHB_ACTIVE_TRANSACTION,
> XHB_PREPARED_TRANSACTION,
> XHB_IDLE_IN_TRANSACTION,
> XHB_XMIN_ACTIVE_TRANSACTION,
> XHB_XMIN_IDLE_IN_TRANSACTION,
> XHB_HOT_STANDBY_FEEDBACK,
> XHB_REPLICATION_SLOT,
> }
Another one:
Currently GetXidHorizonBlocker() selects only one blocker (based on the enum priority) even though multiple independent sources could hold back the xmin horizon simultaneously. For example, it is possible to have both a prepared transaction and a replication slot preventing the horizon from advancing.
Have you considered reporting all detected blockers instead of just the highest-priority one? Returning only a single entry might hide other relevant blockers from the user.
Currently GetXidHorizonBlocker() selects only one blocker (based on the enum priority) even though multiple independent sources could hold back the xmin horizon simultaneously. For example, it is possible to have both a prepared transaction and a replication slot preventing the horizon from advancing.
Have you considered reporting all detected blockers instead of just the highest-priority one? Returning only a single entry might hide other relevant blockers from the user.
Thanks
On Thu, Feb 5, 2026 at 12:40 PM Shinya Kato <shinya11.kato@gmail.com> wrote:
HI,
Sorry for the late reply. I've updated the patch to follow Sami's
recommended approach.
Overview:
- Instead of modifying ComputeXidHorizons(), this patch introduces two
new functions: GetXidHorizonBlockers() and GetXidHorizonBlocker().
- GetXidHorizonBlockers() retrieves all potential blockers. This API
design leaves open the possibility of exposing this information
through a dynamic statistics view in the future [0].
- GetXidHorizonBlocker() selects the highest-priority blocker from the
candidates returned by GetXidHorizonBlockers().
- Priority is defined in the XidHorizonBlockerType enum. By
distinguishing whether the blocker matches the horizon via xid or
xmin, the appropriate blocker is selected.
Changes addressed from review comments:
- Fixed unstable regression test (Fujii-san's and Andres's comments).
- When multiple blockers share the same horizon, the blocker with the
highest priority is now selected for output (Fujii-san's comment).
- Removed unnecessary code (Fujii-san's comment).
- Distinguished between active transactions and idle-in-transaction
sessions, and added tests for both (Sami's and Wenhui's comments).
- Added a trailing comma to the last value of the enum (Sami's comment).
- Added a new function GetXidHorizonBlockers(), modeled after
BackendXidGetPid(), instead of modifying ComputeXidHorizons() (Sami's
comment).
- Added a test for a SERIALIZABLE transaction (Sami's comment).
Not addressed:
- Did not switch from int to pid_t for the pid type, because int is
used consistently throughout the PostgreSQL codebase for this purpose
(Sami's comment).
Other changes:
- Changed the TAP test to use VACUUM (VERBOSE) instead of autovacuum.
[0] https://www.postgresql.org/message-id/CAAaqYe9Dy9sicKg3xzCQUMK3VLdEP39g9nMGZheqtFYfNiO5Bg%40mail.gmail.com
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Japin Li <japinli@hotmail.com>
Дата:
On Mon, 16 Mar 2026 at 15:59, wenhui qiu wrote:
> HI Shinya
>> typedef enum XidHorizonBlockerType
>> {
>> XHB_NONE = 0,
>> XHB_ACTIVE_TRANSACTION,
>> XHB_IDLE_IN_TRANSACTION,
>> XHB_PREPARED_TRANSACTION,
>> XHB_XMIN_ACTIVE_TRANSACTION,
>> XHB_XMIN_IDLE_IN_TRANSACTION,
>> XHB_HOT_STANDBY_FEEDBACK,
>> XHB_REPLICATION_SLOT,
>> }
> Thank you for your working on this ,I have another small suggestion
> The priority ordering encoded in XidHorizonBlockerType determines which blocker gets reported when multiple candidates
> exist. In particular:
>
> ACTIVE_TRANSACTION
> IDLE_IN_TRANSACTION
> PREPARED_TRANSACTION
>
> Prepared transactions are currently ranked after idle-in-transaction sessions. Operationally, prepared transactions are
> often harder for DBAs to resolve than idle sessions, so it might be worth clarifying the rationale behind this ordering
> or reconsidering whether prepared transactions should have higher priority.
Agreed. Explaining the reason for this priority is very helpful.
>> typedef enum XidHorizonBlockerType
>> {
>> XHB_NONE = 0,
>> XHB_ACTIVE_TRANSACTION,
>> XHB_PREPARED_TRANSACTION,
>> XHB_IDLE_IN_TRANSACTION,
>> XHB_XMIN_ACTIVE_TRANSACTION,
>> XHB_XMIN_IDLE_IN_TRANSACTION,
>> XHB_HOT_STANDBY_FEEDBACK,
>> XHB_REPLICATION_SLOT,
>> }
> Another one:
> Currently GetXidHorizonBlocker() selects only one blocker (based on the enum priority) even though multiple independent
> sources could hold back the xmin horizon simultaneously. For example, it is possible to have both a prepared transaction
> and a replication slot preventing the horizon from advancing.
> Have you considered reporting all detected blockers instead of just the highest-priority one? Returning only a single
> entry might hide other relevant blockers from the user.
>
I'm also curious — why don't we list all the blockers? Did I miss anything?
> Thanks
>
> On Thu, Feb 5, 2026 at 12:40 PM Shinya Kato wrote:
>
> HI,
>
> Sorry for the late reply. I've updated the patch to follow Sami's
> recommended approach.
>
> Overview:
> - Instead of modifying ComputeXidHorizons(), this patch introduces two
> new functions: GetXidHorizonBlockers() and GetXidHorizonBlocker().
> - GetXidHorizonBlockers() retrieves all potential blockers. This API
> design leaves open the possibility of exposing this information
> through a dynamic statistics view in the future [0].
> - GetXidHorizonBlocker() selects the highest-priority blocker from the
> candidates returned by GetXidHorizonBlockers().
> - Priority is defined in the XidHorizonBlockerType enum. By
> distinguishing whether the blocker matches the horizon via xid or
> xmin, the appropriate blocker is selected.
>
> Changes addressed from review comments:
> - Fixed unstable regression test (Fujii-san's and Andres's comments).
> - When multiple blockers share the same horizon, the blocker with the
> highest priority is now selected for output (Fujii-san's comment).
> - Removed unnecessary code (Fujii-san's comment).
> - Distinguished between active transactions and idle-in-transaction
> sessions, and added tests for both (Sami's and Wenhui's comments).
> - Added a trailing comma to the last value of the enum (Sami's comment).
> - Added a new function GetXidHorizonBlockers(), modeled after
> BackendXidGetPid(), instead of modifying ComputeXidHorizons() (Sami's
> comment).
> - Added a test for a SERIALIZABLE transaction (Sami's comment).
>
> Not addressed:
> - Did not switch from int to pid_t for the pid type, because int is
> used consistently throughout the PostgreSQL codebase for this purpose
> (Sami's comment).
>
> Other changes:
> - Changed the TAP test to use VACUUM (VERBOSE) instead of autovacuum.
>
> [0] https://www.postgresql.org/message-id/CAAaqYe9Dy9sicKg3xzCQUMK3VLdEP39g9nMGZheqtFYfNiO5Bg%40mail.gmail.com
>
> --
> Best regards,
> Shinya Kato
> NTT OSS Center
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: Report oldest xmin source when autovacuum cannot remove tuples
Thank you for your feedback!
On Mon, Mar 16, 2026 at 8:19 PM Japin Li wrote:
>
> On Mon, 16 Mar 2026 at 15:59, wenhui qiu wrote:
> > HI Shinya
> >> typedef enum XidHorizonBlockerType
> >> {
> >> XHB_NONE = 0,
> >> XHB_ACTIVE_TRANSACTION,
> >> XHB_IDLE_IN_TRANSACTION,
> >> XHB_PREPARED_TRANSACTION,
> >> XHB_XMIN_ACTIVE_TRANSACTION,
> >> XHB_XMIN_IDLE_IN_TRANSACTION,
> >> XHB_HOT_STANDBY_FEEDBACK,
> >> XHB_REPLICATION_SLOT,
> >> }
> > Thank you for your working on this ,I have another small suggestion
> > The priority ordering encoded in XidHorizonBlockerType determines which blocker gets reported when multiple candidates
> > exist. In particular:
> >
> > ACTIVE_TRANSACTION
> > IDLE_IN_TRANSACTION
> > PREPARED_TRANSACTION
> >
> > Prepared transactions are currently ranked after idle-in-transaction sessions. Operationally, prepared transactions are
> > often harder for DBAs to resolve than idle sessions, so it might be worth clarifying the rationale behind this ordering
> > or reconsidering whether prepared transactions should have higher priority.
>
> Agreed. Explaining the reason for this priority is very helpful.
We always pick a blocker from the xid-match group first (it is the
transaction actually holding the horizon, while the xmin-match entries
are just held back by it). Within the xid-match group, the
active/idle/prepared order never matters: a given xid is owned by only
one backend, so when the horizon equals a proc's xid there is only one
matching entry, and it is exactly one of active, idle, or prepared. So
moving prepared ahead of idle would not change which blocker we
report.
> >> typedef enum XidHorizonBlockerType
> >> {
> >> XHB_NONE = 0,
> >> XHB_ACTIVE_TRANSACTION,
> >> XHB_PREPARED_TRANSACTION,
> >> XHB_IDLE_IN_TRANSACTION,
> >> XHB_XMIN_ACTIVE_TRANSACTION,
> >> XHB_XMIN_IDLE_IN_TRANSACTION,
> >> XHB_HOT_STANDBY_FEEDBACK,
> >> XHB_REPLICATION_SLOT,
> >> }
> > Another one:
> > Currently GetXidHorizonBlocker() selects only one blocker (based on the enum priority) even though multiple independent
> > sources could hold back the xmin horizon simultaneously. For example, it is possible to have both a prepared transaction
> > and a replication slot preventing the horizon from advancing.
> > Have you considered reporting all detected blockers instead of just the highest-priority one? Returning only a single
> > entry might hide other relevant blockers from the user.
> >
>
> I'm also curious — why don't we list all the blockers? Did I miss anything?
I did think about this, but I would like to keep reporting one blocker
in the VACUUM log, for two reasons.
First, the log can get very large. In Sami's earlier example [0], a
pgbench run had many backends all sharing the same xmin while only one
idle-in-transaction backend actually owned the cutoff xid. Reporting
every blocker would print 20+ lines, almost all of them just victims
of the same root cause, which makes the log harder to read, not
easier.
Second, the one blocker we report is the root cause (the xid owner).
Once the DBA resolves it, the next VACUUM will show the next blocker
if one remains.
This is also why the code is split into GetXidHorizonBlockers(), which
already collects every candidate, and GetXidHorizonBlocker(), which
picks the highest-priority one for the log. The "show everything" case
is what I would like to expose later through a dynamic statistics
view, where a full list makes more sense than in a VACUUM log line.
I've rebased the patch.
P.S. It might be better to use bottom posting instead of top posting [1].
[0] https://www.postgresql.org/message-id/CAA5RZ0sjMgMo4Xg-niyyF-CpkQ_CK6uOfNKYT%3D9RmiBkAxQkbQ%40mail.gmail.com
[1] https://wiki.postgresql.org/wiki/Mailing_Lists#Email_etiquette_mechanics
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Japin Li <japinli@hotmail.com>
Дата:
On Fri, 22 May 2026 at 22:05, Shinya Kato wrote:
> Thank you for your feedback!
>
> On Mon, Mar 16, 2026 at 8:19 PM Japin Li wrote:
>>
>> On Mon, 16 Mar 2026 at 15:59, wenhui qiu wrote:
>> > HI Shinya
>> >> typedef enum XidHorizonBlockerType
>> >> {
>> >> XHB_NONE = 0,
>> >> XHB_ACTIVE_TRANSACTION,
>> >> XHB_IDLE_IN_TRANSACTION,
>> >> XHB_PREPARED_TRANSACTION,
>> >> XHB_XMIN_ACTIVE_TRANSACTION,
>> >> XHB_XMIN_IDLE_IN_TRANSACTION,
>> >> XHB_HOT_STANDBY_FEEDBACK,
>> >> XHB_REPLICATION_SLOT,
>> >> }
>> > Thank you for your working on this ,I have another small suggestion
>> > The priority ordering encoded in XidHorizonBlockerType determines which blocker gets reported when multiple candidates
>> > exist. In particular:
>> >
>> > ACTIVE_TRANSACTION
>> > IDLE_IN_TRANSACTION
>> > PREPARED_TRANSACTION
>> >
>> > Prepared transactions are currently ranked after idle-in-transaction sessions. Operationally, prepared transactions are
>> > often harder for DBAs to resolve than idle sessions, so it might be worth clarifying the rationale behind this ordering
>> > or reconsidering whether prepared transactions should have higher priority.
>>
>> Agreed. Explaining the reason for this priority is very helpful.
>
> We always pick a blocker from the xid-match group first (it is the
> transaction actually holding the horizon, while the xmin-match entries
> are just held back by it). Within the xid-match group, the
> active/idle/prepared order never matters: a given xid is owned by only
> one backend, so when the horizon equals a proc's xid there is only one
> matching entry, and it is exactly one of active, idle, or prepared. So
> moving prepared ahead of idle would not change which blocker we
> report.
>
>> >> typedef enum XidHorizonBlockerType
>> >> {
>> >> XHB_NONE = 0,
>> >> XHB_ACTIVE_TRANSACTION,
>> >> XHB_PREPARED_TRANSACTION,
>> >> XHB_IDLE_IN_TRANSACTION,
>> >> XHB_XMIN_ACTIVE_TRANSACTION,
>> >> XHB_XMIN_IDLE_IN_TRANSACTION,
>> >> XHB_HOT_STANDBY_FEEDBACK,
>> >> XHB_REPLICATION_SLOT,
>> >> }
>> > Another one:
>> > Currently GetXidHorizonBlocker() selects only one blocker (based on the enum priority) even though multiple independent
>> > sources could hold back the xmin horizon simultaneously. For example, it is possible to have both a prepared transaction
>> > and a replication slot preventing the horizon from advancing.
>> > Have you considered reporting all detected blockers instead of just the highest-priority one? Returning only a single
>> > entry might hide other relevant blockers from the user.
>> >
>>
>> I'm also curious — why don't we list all the blockers? Did I miss anything?
>
> I did think about this, but I would like to keep reporting one blocker
> in the VACUUM log, for two reasons.
>
> First, the log can get very large. In Sami's earlier example [0], a
> pgbench run had many backends all sharing the same xmin while only one
> idle-in-transaction backend actually owned the cutoff xid. Reporting
> every blocker would print 20+ lines, almost all of them just victims
> of the same root cause, which makes the log harder to read, not
> easier.
>
> Second, the one blocker we report is the root cause (the xid owner).
> Once the DBA resolves it, the next VACUUM will show the next blocker
> if one remains.
>
> This is also why the code is split into GetXidHorizonBlockers(), which
> already collects every candidate, and GetXidHorizonBlocker(), which
> picks the highest-priority one for the log. The "show everything" case
> is what I would like to expose later through a dynamic statistics
> view, where a full list makes more sense than in a VACUUM log line.
>
>
> I've rebased the patch.
>
Thanks for updating the patch. LGTM. Just one nitpick.
+ int pid; /* backend pid (0 for slots) */
Per the code, the prepared transaction is also associated with a PID of zero.
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: Report oldest xmin source when autovacuum cannot remove tuples
On Sat, May 23, 2026 at 2:22 PM Shinya Kato wrote: > Additionally, I forgot to update meson.build, which caused the tests > to fail. I have fixed that in the attached patch. Oops, I made a slight mistake. Fixed. -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
Hi
Thank you updating the path,LGTM
Thanks
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
On Sat, May 23, 2026 at 10:35 PM Laurenz Albe wrote: > The patch looks fine to me too. Thanks all for the reviews and LGTMs! Before moving this forward, I noticed there is one thing in the patch that I should fix first. When hot_standby_feedback=on, the location where the standby's xmin is recorded on the primary depends on whether physical replication slot is used: - Without a replication slot: the xmin is held on the walsender's PGPROC - With a replication slot: the xmin is held on the replication slot itself I summarized this behavior in my blog: https://dev.to/shinyakato_/4-causes-of-table-bloat-in-postgresql-and-how-to-address-them-3ec9 The current patch reports the latter case as XHB_REPLICATION_SLOT with the message "logical replication slot", which is misleading because it is actually a physical slot used by a standby with hot_standby_feedback=on. I will fix this and post an updated patch later. -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
> I guess the overhead of one more scan of the process array for every autovacuum > run if "log_autovacuum_min_duration" is non-zero (which is the default) > is acceptable. Could vacuum compute the blocker during ComputeXidHorizons and consume it at log time? Avoids the extra scan, and binds the blocker to the horizon vacuum used for pruning. Scott Ray
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
On Sat, May 30, 2026 at 11:31 AM Scott Ray wrote: > > > I guess the overhead of one more scan of the process array for every autovacuum > > run if "log_autovacuum_min_duration" is non-zero (which is the default) > > is acceptable. > > > Could vacuum compute the blocker during ComputeXidHorizons and consume it at log time? > Avoids the extra scan, and binds the blocker to the horizon vacuum used for pruning. As Sami suggested in [0], I think this design is a cleaner approach because it separates the responsibilities of ComputeXidHorizons and the calculation of vacuum blockers. [0] https://www.postgresql.org/message-id/CAA5RZ0s%2BUUXekbeGcC-H71kW%3DMfeaUCOV%3DyEWX94NXViO2-%3DpA%40mail.gmail.com -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
> What I would want to investigate after seeing such a signal is not > necessarily what happened to be blocking that particular VACUUM > operation at some earlier point, but what is holding the xid horizon > back now. For that purpose, a view exposing the current xid/xmin > holders seems more useful and less misleading than adding a > best-effort blocker guess to the VACUUM log. I've been working on a view like this. It shows the horizon contribution for each backend, prepared xact, replication slot, and HSF walsender, broken down by class. It also shows - for each contributor - how the horizon would shift if that holder were removed. Shinya said [1] that we could have a view in the future. We could have both the logging and the view call a single function that reads the procArray and other sources to gather the horizon information. I think the logging and the view would complement each other. Should I start another thread? [1] https://www.postgresql.org/message-id/CAOzEurTNVkvvscKeEOy0WwfzyqO+J_MyXwkjRteJ_zyydteKCQ@mail.gmail.com -- Scott Ray
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
On Wed, Jun 3, 2026 at 8:34 AM Sami Imseih wrote: > > Hi, > > > This may be just my personal preference, but I'd rather see > > information about xid horizon retention exposed through a SQL-visible > > interface than added to the VACUUM log. > > > > VACUUM VERBOSE already reports the removable cutoff and how old it was > > when the operation ended. That seems sufficient as a signal that the > > xid horizon is being held back. > > > > What I would want to investigate after seeing such a signal is not > > necessarily what happened to be blocking that particular VACUUM > > operation at some earlier point, but what is holding the xid horizon > > back now. For that purpose, a view exposing the current xid/xmin > > holders seems more useful and less misleading than adding a > > best-effort blocker guess to the VACUUM log. > > +1, I also had a similar comment at the bottom of [1], where this information > is better to be exposed in SQL for proactive monitoring. I agree that exposing xid horizon retention information via a SQL-visible interface is valuable. However, I believe reporting it in the VACUUM log is also important: a view only shows the current state, so once a blocker has gone away there is no way to determine, after the fact, what was holding the horizon back at the time a particular VACUUM ran. Logs are the only durable record we have for that kind of post-hoc analysis. That said, I share the concern about emitting best-effort information in the VACUUM log, which otherwise reports facts observed during the operation. Would it be acceptable if we reported the exact blocker -- captured at the moment OldestXmin is computed -- rather than a best-effort guess reconstructed afterwards? -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
On Wed, Jun 3, 2026 at 10:05 AM Scott Ray wrote: > I've been working on a view like this. It shows the horizon > contribution for each backend, prepared xact, replication slot, and > HSF walsender, broken down by class. It also shows - for each > contributor - how the horizon would shift if that holder were > removed. > > Shinya said [1] that we could have a view in the future. We could > have both the logging and the view call a single function that reads > the procArray and other sources to gather the horizon information. I > think the logging and the view would complement each other. > > Should I start another thread? My mild preference would be to keep the discussion on this thread, since the shared function design is central to both the log and the view and may be easier to keep aligned in one place. That said, I'm not strongly attached to that, so please pick whichever feels more convenient. -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
HI Shinya
> I agree that exposing xid horizon retention information via a
> SQL-visible interface is valuable. However, I believe reporting it
> in the VACUUM log is also important: a view only shows the current
> state, so once a blocker has gone away there is no way to determine,
> after the fact, what was holding the horizon back at the time a
> particular VACUUM ran. Logs are the only durable record we have for
> that kind of post-hoc analysis.
Agree +1,There's no denying that checking SQL is easier than checking logs. Logs are also important though. In fact, I think we should apply this patch first and implement the SQL later.
> SQL-visible interface is valuable. However, I believe reporting it
> in the VACUUM log is also important: a view only shows the current
> state, so once a blocker has gone away there is no way to determine,
> after the fact, what was holding the horizon back at the time a
> particular VACUUM ran. Logs are the only durable record we have for
> that kind of post-hoc analysis.
Agree +1,There's no denying that checking SQL is easier than checking logs. Logs are also important though. In fact, I think we should apply this patch first and implement the SQL later.
Thanks
On Wed, Jun 3, 2026 at 9:25 AM Shinya Kato <shinya11.kato@gmail.com> wrote:
On Wed, Jun 3, 2026 at 10:05 AM Scott Ray <scott@scottray.io> wrote:
> I've been working on a view like this. It shows the horizon
> contribution for each backend, prepared xact, replication slot, and
> HSF walsender, broken down by class. It also shows - for each
> contributor - how the horizon would shift if that holder were
> removed.
>
> Shinya said [1] that we could have a view in the future. We could
> have both the logging and the view call a single function that reads
> the procArray and other sources to gather the horizon information. I
> think the logging and the view would complement each other.
>
> Should I start another thread?
My mild preference would be to keep the discussion on this thread,
since the shared function design is central to both the log and the
view and may be easier to keep aligned in one place. That said, I'm
not strongly attached to that, so please pick whichever feels more
convenient.
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Japin Li <japinli@hotmail.com>
Дата:
On Wed, 03 Jun 2026 at 10:32, wenhui qiu wrote: > HI Shinya >> I agree that exposing xid horizon retention information via a >> SQL-visible interface is valuable. However, I believe reporting it >> in the VACUUM log is also important: a view only shows the current >> state, so once a blocker has gone away there is no way to determine, >> after the fact, what was holding the horizon back at the time a >> particular VACUUM ran. Logs are the only durable record we have for >> that kind of post-hoc analysis. > Agree +1,There's no denying that checking SQL is easier than checking logs. Logs are also important though. In fact, I > think we should apply this patch first and implement the SQL later. > +1 for this idea. I don't think they conflict with each other — they just provide the same content from different perspectives. > Thanks > > On Wed, Jun 3, 2026 at 9:25 AM Shinya Kato wrote: > > On Wed, Jun 3, 2026 at 10:05 AM Scott Ray wrote: > > I've been working on a view like this. It shows the horizon > > contribution for each backend, prepared xact, replication slot, and > > HSF walsender, broken down by class. It also shows - for each > > contributor - how the horizon would shift if that holder were > > removed. > > > > Shinya said [1] that we could have a view in the future. We could > > have both the logging and the view call a single function that reads > > the procArray and other sources to gather the horizon information. I > > think the logging and the view would complement each other. > > > > Should I start another thread? > > My mild preference would be to keep the discussion on this thread, > since the shared function design is central to both the log and the > view and may be easier to keep aligned in one place. That said, I'm > not strongly attached to that, so please pick whichever feels more > convenient. > > -- > Best regards, > Shinya Kato > NTT OSS Center -- Regards, Japin Li ChengDu WenWu Information Technology Co., Ltd.
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Jacob Champion <jacob.champion@enterprisedb.com>
Дата:
(A colleague pointed me at this thread just now, because I somehow missed it, but I've also been playing around with a solution for this recently. Your patches are much farther along than mine -- hooray!) On Tue, Jun 2, 2026 at 6:11 PM Shinya Kato wrote: > I agree that exposing xid horizon retention information via a > SQL-visible interface is valuable. However, I believe reporting it > in the VACUUM log is also important: a view only shows the current > state, so once a blocker has gone away there is no way to determine, > after the fact, what was holding the horizon back at the time a > particular VACUUM ran. Logs are the only durable record we have for > that kind of post-hoc analysis. +1. I'd *really* like to have this information logged at the point that VACUUM is blocked; it'll help during support escalations (or prevent them!) in a way that a view cannot. That's not to say we couldn't also have a view, of course. > That said, I share the concern about emitting best-effort > information in the VACUUM log, which otherwise reports facts > observed during the operation. Would it be acceptable if we > reported the exact blocker -- captured at the moment OldestXmin is > computed -- rather than a best-effort guess reconstructed > afterwards? I don't want to weigh in very strongly here; you've all been thinking about it for longer than I have. So, taking off the committer hat and putting my user hat on: I ran into the same decision between 1) tracking the origin during horizon calculation and 2) attempting to reconstruct it after the fact. I decided, for my own patch, that I'd rather track them during horizon calculation. The cases where I really need these logs are high-stress, chaotic situations where things are falling apart, and if the database's answer to "what's causing the problem?" is ever "I don't know, you better run VACUUM again", I think that's likely to spike my blood pressure. As discussed above, though, this approach leads to a collision issue. So I put the patch down before PGConf.dev, trying to figure out how best to solve that. (That said, there's nothing wrong with getting a good solution in and working on a better one, as long as the first patch doesn't make the second one harder. Thank you for working on this!) --Jacob
Re: Report oldest xmin source when autovacuum cannot remove tuples
> > Shinya said [1] that we could have a view in the future. We could > > have both the logging and the view call a single function that reads > > the procArray and other sources to gather the horizon information. I > > think the logging and the view would complement each other. > > > > Should I start another thread? > > My mild preference would be to keep the discussion on this thread, > since the shared function design is central to both the log and the > view and may be easier to keep aligned in one place. That said, I'm > not strongly attached to that, so please pick whichever feels more > convenient. I attached a patch that uses a helper function that could also be used for a view, but I don't think it's necessary immediately, because refactoring later wouldn't be difficult. -- Scott Ray
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Sami Imseih <samimseih@gmail.com>
Дата:
>> Additionally, I forgot to update meson.build, which caused the tests
>> to fail. I have fixed that in the attached patch.
> Oops, I made a slight mistake. Fixed.
Thanks for the updated patch!
I agree there is value in logging this information during
vacuum/autovacuum, as unlike a view, it provides the ability to
investigate historically what was blocking vacuum. Having both the
vacuum logging and the view seems like a good combination to me.
In terms of v5, I have some comments:
1/ Reporting the GID of a prepared transaction.
This seems unnecessary. The logged xid is sufficient since a DBA
can look up the GID via pg_prepared_xacts using the "transaction"
column. I think we can remove GetPreparedTransactionGid() and
just report the xid.
2/ Reporting the application_name of the standby.
This could be valuable assuming the user sets application_name in the
primary_conninfo string to make the standby distinguishable. The
documentation [1] says this "should be set" for physical standbys,
and in practice most deployments do so since
synchronous_standby_names matches on it.
However, instead of GetStandbyAppname(), can we use
pgstat_get_beentry_by_proc_number() to get the application name and
set it in dst->name while holding the shared ProcArrayLock? This is
safe if we call pgstat_fetch_stat_numbackends() beforehand to prime
the local backend status cache. The subsequent lookup is just a
bsearch on local memory, so it adds negligible time under the lock.
3/ Over-allocation in GetXidHorizonBlockers().
+ /*
+ * Allocate enough space for every PGPROC plus all replication slots. This
+ * is a generous upper bound (typically only 0-2 entries are returned),
+ * but keeps the logic simple for a diagnostic function that runs
+ * infrequently.
+ */
+ max_blockers = arrayP->maxProcs + max_replication_slots;
+ result = palloc0_array(XidHorizonBlocker, max_blockers);
This looks wasteful, especially with large max_connections. In
practice only 1-3 entries are returned. Can we start with a small
allocation (say 8) and repalloc when needed?
4/ Simplify the loop body by removing candidate_* temporaries.
The values we set in dst don't need to be tracked in separate
variables. If dst gets populated for the proc, we can just do:
```
if (dst)
{
dst->pid = proc->pid;
dst->xid = horizon;
dst->proc_number = pgprocno;
}
```
at the end of each iteration.
5/ GetXidHorizonBlocker() priority scan.
+/*
+ * Get the highest-priority blocker holding back the xid horizon.
+ *
+ * Returns true and stores the blocker in *blocker if any are found.
+ */
The priority scan makes sense and addresses the concern I raised
earlier [2] about reporting the wrong blocker due to ProcArray
ordering. Without it we report whichever blocker happens to come
first in ProcArray order. If an xmin-holder sits at a lower index
than the xid-holder, we would report the less actionable one. The
xid-holder is more useful to surface because killing that single
transaction advances the horizon, whereas xmin-holders only matter
once all of them release.
One small optimization: exit the loop early once we find an xid-match
type, since nothing can beat it:
for (int i = 0; i < nblockers; i++)
{
if (best == NULL || blockers[i].type < best->type)
{
best = &blockers[i];
/* xid-match types can't be beaten, stop early */
if (best->type <= XHB_PREPARED_TRANSACTION)
break;
}
}
Finally, the infrastructure added here (GetXidHorizonBlockers,
XidHorizonBlocker struct, the enum-based priority) will also underpin
the future SQL-callable view for real-time blocker reporting, so I
think what is being done here is good for that case also. I would
also think that GetXidHorizonBlockers() and friends should be a
separate patch, and the vacuum logging and future SQL view work can
build off of it.
[1] https://www.postgresql.org/docs/current/runtime-config-replication.html#GUC-PRIMARY-CONNINFO
[2] https://www.postgresql.org/message-id/CAA5RZ0sjMgMo4Xg-niyyF-CpkQ_CK6uOfNKYT%3D9RmiBkAxQkbQ%40mail.gmail.com
--
Sami Imseih
Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
I have already posted the version addressing the previous review
comments. On top of that, v7 includes several further fixes I found
while re-examining the code myself, which are summarized below.
Correctness
-----------
- Scope the blocker scan to the relation's horizon kind.
GetXidHorizonBlocker() now takes the Relation and derives the
GlobalVisHorizonKind, so the ProcArray scan applies the same
per-database filter as ComputeXidHorizons() [1] (other-database
backends only hold back the shared horizon, plus
PROC_AFFECTS_ALL_HORIZONS), and a slot's catalog_xmin is only treated
as a blocker for the shared/catalog horizons. The temp-table horizon
(held only by our own backend) now returns no blocker. Previously a
backend in an unrelated database, or a logical slot's catalog_xmin
against a data-only horizon, could be reported.
- Compare against the slot's effective xmin, not data.xmin. The
horizon is aggregated from effective_xmin/effective_catalog_xmin [2],
so the scan now reads those. With data.xmin a blocker was missed
whenever the two diverge. For example, while a logical slot that
exports a snapshot is being created, effective_xmin is set but
data.xmin is left invalid. Reading effective_xmin is also safe for
physical slots, where it is set together with data.xmin and retained
after disconnect [3].
- Cover all replication slots and skip invalidated ones. The scan
iterates the full slot array (including repack slots) and skips
data.invalidated != RS_INVAL_NONE, matching
ReplicationSlotsComputeRequiredXmin() [2]. The worst-case result array
was resized accordingly.
- Classify active vs. idle-in-transaction from backend state, not
wait_event_info. A PGPROC cannot tell an idle-in-transaction session
from one blocked on client I/O (both wait on WAIT_EVENT_CLIENT_READ),
so e.g. an in-progress COPY FROM STDIN was logged as "idle in
transaction". The active/idle split is now resolved after the scan
locks are released, from PgBackendStatus.st_state, the same source as
pg_stat_activity.state [4].
Cleanup
-------
- Removed the unreachable XHB_NONE enum value (and its vacuumlazy.c
switch case).
- Removed the unused storage/lock.h include from procarray.h
(VirtualTransactionId comes via storage/standby.h).
- Report the slot blocker's xid as the horizon directly, rather than
recomputing it from the slot's effective xmin or catalog_xmin.
Test (014_log_vacuum_blockers.pl)
---------------------------------
- wal_receiver_status_interval = 100ms -> 1s. The GUC's unit is
seconds, so 100ms rounded down to 0, which disables periodic
hot-standby feedback. The feedback cases previously passed only by
chance, via the one-shot message sent at walreceiver startup.
- Made the hot-standby-feedback cases deterministic: wait for the
standby reader's snapshot to be reflected in the feedback (walsender
backend_xmin, or the slot's xmin) before the DELETE, rather than
polling for merely non-null.
- Disconnected-physical-slot case: issue a fresh INSERT/DELETE after
the standby disconnects, since terminating the reader may have let a
final feedback advance the frozen slot xmin past the earlier DELETE.
- Switched wait_for_catchup(..., 'replay', lsn('flush')) to
wait_for_replay_catchup().
[1] https://github.com/postgres/postgres/blob/dbaa4dc3c8dd77a0e1c977024d4ae150e00456b3/src/backend/storage/ipc/procarray.c#L1796-L1799
[2] https://github.com/postgres/postgres/blob/dbaa4dc3c8dd77a0e1c977024d4ae150e00456b3/src/backend/replication/slot.c#L1257-L1288
[3] https://github.com/postgres/postgres/blob/dbaa4dc3c8dd77a0e1c977024d4ae150e00456b3/src/backend/replication/walsender.c#L2648-L2663
[4] https://github.com/postgres/postgres/blob/dbaa4dc3c8dd77a0e1c977024d4ae150e00456b3/src/include/utils/backend_status.h#L24-L34
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Дата:
Hello,
I looked at this a bit further and had several comments.
> if (kind != VISHORIZON_SHARED &&
> + proc->databaseId != MyDatabaseId &&
> + MyDatabaseId != InvalidOid &&
> + !(statusFlags & PROC_AFFECTS_ALL_HORIZONS) &&
> + !in_recovery)
> + continue;
First, although the comment says this mirrors the existing logic, it
also adds extra conditions. I think it would be clearer to separate
the common part from the function-specific part, so that the former
remains almost a direct copy of the existing logic and the latter is
handled separately.
Related to that, I am worried that future changes to
ComputeXidHorizons() could easily leave GetXidHorizonBlockers() out of
sync. Would it be possible to factor the common decision logic out
into a suitably named helper that both functions could use?
Second, as far as I can tell, in_recovery is not a per-process
condition, but rather controls whether the other filtering conditions
are applied at all. Flattening those two concerns into a single
condition makes the logic rather difficult to follow, particularly
because the underlying filtering rules are already fairly involved. As
written, it appears that recovery mode bypasses all of the other
filtering conditions, so all processes are considered by the
subsequent checks. Is that really the intended behavior?
In addition, I am also not sure the recovery case is handled
sufficiently here. As far as I understand, ComputeXidHorizons() does
not rely only on the proc array during recovery; it also considers the
oldest xmin from KnownAssignedXids. If the horizon is determined by
that value, GetXidHorizonBlockers() may not be able to find a matching
PGPROC entry. If this function is intended to explain the horizon
computed by ComputeXidHorizons(), I think the recovery case needs
either matching handling or an explicit comment explaining why it is
safe to ignore that source.
Also, RecoveryInProgress() can change from true to false while the
function is running. So I think it would be useful to explain
somewhere why it is safe to keep using the saved value. I do not see
such an explanation in ComputeXidHorizons() either, but this code made
me think about it.
> + if (TransactionIdEquals(proc_xid, horizon))
> + {
> + dst = &result[count++];
....
> + dst->type = XHB_XMIN_ACTIVE_TRANSACTION;
> + }
> +
> + if (dst)
> + {
This may just be a matter of taste, but I wonder whether this part
could be written a bit more clearly. For example, the first
if/else-if chain could determine only the blocker type, ending with an
"else continue". Then the common work, including allocating dst, could
be done afterwards in one place. I think that would make the flow a
bit easier to follow.
One more thought about the allocation strategy here. The fixed-size
"name" field seems to dominate the size of XidHorizonBlocker, but the
name is filled only after releasing ProcArrayLock. So I wonder whether
it needs to be embedded in every entry collected under the lock.
If "name" were stored separately, for example as a char * allocated
only when needed, the per-entry size would be much smaller. Then a
single array of XidHorizonBlocker entries preallocated before taking
ProcArrayLock would be less concerning. For example, with 1000
entries, an entry of around 24 bytes would be about 24KB, and the
strings would consume space only for entries that actually need one.
Another possible approach would be to collect only the lock-protected
fields in a small temporary array while holding ProcArrayLock, and
then build the full result array after releasing the lock.
> + active_proc = s->active_proc;
> + invalidated = s->data.invalidated != RS_INVAL_NONE;
> + SpinLockRelease(&s->mutex);
> +
> + /* Invalidated slots no longer hold back the horizon. */
> + if (invalidated)
> + continue;
This is a very minor point, but I wonder whether it would be a bit
cleaner to copy s->data.invalidated under the spinlock and perform the
comparison afterwards, keeping the locked section limited to copying
shared fields. I know there are other places that cache the boolean
result directly, but unless the boolean value is going to be reused, I
think comparing it afterwards reads a little more naturally.
Regards,
--
Kyotaro Horiguchi
NTT Open Source Software Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Sat, Jun 27, 2026 at 1:08 AM Shinya Kato wrote: > > I have already posted the version addressing the previous review > comments. On top of that, v7 includes several further fixes I found > while re-examining the code myself, which are summarized below. Thanks for working on this, and sorry for being late. A big +1 to reporting what's holding the vacuum back. Today one has to query a bunch of different views, and it's not always obvious which ones to look at, so reporting the blocker reason in the logs (perhaps also in the progress report) is very useful IMO. It helps quickly diagnose the root cause, possibly act on it, and also helps with post-hoc analysis. My main concern is the additional proc array scan and the lock it takes. ProcArrayLock is one of the most contended locks in production systems with hundreds or thousands of connections. With many workers vacuuming concurrently across hundreds of tables, I expect this extra lock acquisition to show up in the contention path. ComputeXidHorizons() already takes ProcArrayLock and has all the information about who is blocking the vacuum, so I think we can capture the blocker right there and get the reason almost for free, without a second scan. One thing worth mentioning is that we can only ever report a "possible" reason. There's an inherent race - by the time we report a blocker, it may already be gone. So this is best-effort information. The other concern is timing. The patch reports the blocker after the vacuum has finished. With hundreds of GB of tables and indexes, where vacuum can run for hours, reporting up front is far more useful than learning at the end that vacuum couldn't remove the tuples. If we capture the blocker when ComputeXidHorizons() computes the horizon, we can tell the user early, while there's still a chance to act on it. I wrote a patch on the same idea about a month ago, then got busy and only noticed this thread now. If it helps, I'm happy to post it. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> ComputeXidHorizons() already takes ProcArrayLock and has all the > information about who is blocking the vacuum, so I think we can > capture the blocker right there and get the reason almost for free, > without a second scan. This idea proved to result in incorrect information. See [1] [1] https://www.postgresql.org/message-id/CAA5RZ0sjMgMo4Xg-niyyF-CpkQ_CK6uOfNKYT%3D9RmiBkAxQkbQ%40mail.gmail.com -- Sami Imseih Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
On Mon, Jun 29, 2026 at 5:22 PM Kyotaro Horiguchi
wrote:
> > if (kind != VISHORIZON_SHARED &&
> > + proc->databaseId != MyDatabaseId &&
> > + MyDatabaseId != InvalidOid &&
> > + !(statusFlags & PROC_AFFECTS_ALL_HORIZONS) &&
> > + !in_recovery)
> > + continue;
>
> First, although the comment says this mirrors the existing logic, it
> also adds extra conditions. I think it would be clearer to separate
> the common part from the function-specific part, so that the former
> remains almost a direct copy of the existing logic and the latter is
> handled separately.
>
> Related to that, I am worried that future changes to
> ComputeXidHorizons() could easily leave GetXidHorizonBlockers() out of
> sync. Would it be possible to factor the common decision logic out
> into a suitably named helper that both functions could use?
Thank you for the review. Agreed. In v8 I factored the per-database
filter into a new helper, ProcAffectsDataHorizon(), that both
ComputeXidHorizons() and GetXidHorizonBlockers() now call, so the
common logic is shared rather than duplicated and cannot drift apart.
The explanatory comment moved to the helper. The function-specific
exclusion (skipping the caller's own proc) is now a separate condition
with its own comment.
> Second, as far as I can tell, in_recovery is not a per-process
> condition, but rather controls whether the other filtering conditions
> are applied at all. Flattening those two concerns into a single
> condition makes the logic rather difficult to follow, particularly
> because the underlying filtering rules are already fairly involved. As
> written, it appears that recovery mode bypasses all of the other
> filtering conditions, so all processes are considered by the
> subsequent checks. Is that really the intended behavior?
Yes, considering all processes during recovery was intended, to mirror
ComputeXidHorizons(), which during recovery considers backends in all
databases for the data horizon because an accurate per-database
horizon cannot be computed then. But your next comment made me
reconsider whether GetXidHorizonBlockers() should handle recovery at
all.
> In addition, I am also not sure the recovery case is handled
> sufficiently here. As far as I understand, ComputeXidHorizons() does
> not rely only on the proc array during recovery; it also considers the
> oldest xmin from KnownAssignedXids. If the horizon is determined by
> that value, GetXidHorizonBlockers() may not be able to find a matching
> PGPROC entry. If this function is intended to explain the horizon
> computed by ComputeXidHorizons(), I think the recovery case needs
> either matching handling or an explicit comment explaining why it is
> safe to ignore that source.
You are right, the KnownAssignedXids case was not handled. The only
caller is VACUUM, which cannot run during recovery, so in v8 I removed
the recovery handling and replaced it with
Assert(!RecoveryInProgress()). A comment on the assertion notes that a
future caller running during recovery (for example a SQL-callable view
usable on a standby) must add recovery handling, including the
KnownAssignedXids source.
> Also, RecoveryInProgress() can change from true to false while the
> function is running. So I think it would be useful to explain
> somewhere why it is safe to keep using the saved value. I do not see
> such an explanation in ComputeXidHorizons() either, but this code made
> me think about it.
Now that the recovery handling is gone, the function no longer uses
RecoveryInProgress() outside the assertion, so your concern about
relying on the saved value no longer applies.
> > + if (TransactionIdEquals(proc_xid, horizon))
> > + {
> > + dst = &result[count++];
> ....
> > + dst->type = XHB_XMIN_ACTIVE_TRANSACTION;
> > + }
> > +
> > + if (dst)
> > + {
>
> This may just be a matter of taste, but I wonder whether this part
> could be written a bit more clearly. For example, the first
> if/else-if chain could determine only the blocker type, ending with an
> "else continue". Then the common work, including allocating dst, could
> be done afterwards in one place. I think that would make the flow a
> bit easier to follow.
Agreed. In v8 the chain determines only the blocker type and ends with
an else continue, and the entry is allocated and filled in one place
afterwards.
> One more thought about the allocation strategy here. The fixed-size
> "name" field seems to dominate the size of XidHorizonBlocker, but the
> name is filled only after releasing ProcArrayLock. So I wonder whether
> it needs to be embedded in every entry collected under the lock.
>
> If "name" were stored separately, for example as a char * allocated
> only when needed, the per-entry size would be much smaller. Then a
> single array of XidHorizonBlocker entries preallocated before taking
> ProcArrayLock would be less concerning. For example, with 1000
> entries, an entry of around 24 bytes would be about 24KB, and the
> strings would consume space only for entries that actually need one.
>
> Another possible approach would be to collect only the lock-protected
> fields in a small temporary array while holding ProcArrayLock, and
> then build the full result array after releasing the lock.
Since v6 the scan collects XidHorizonBlockerCandidate entries with no
name field (around 24 bytes each), and the name is resolved after all
locks are released, only for the single blocker that is actually
reported (see FillXidHorizonBlocker()). I believe this already matches
the second approach you describe. Please let me know if you meant
something more.
> > + active_proc = s->active_proc;
> > + invalidated = s->data.invalidated != RS_INVAL_NONE;
> > + SpinLockRelease(&s->mutex);
> > +
> > + /* Invalidated slots no longer hold back the horizon. */
> > + if (invalidated)
> > + continue;
>
> This is a very minor point, but I wonder whether it would be a bit
> cleaner to copy s->data.invalidated under the spinlock and perform the
> comparison afterwards, keeping the locked section limited to copying
> shared fields. I know there are other places that cache the boolean
> result directly, but unless the boolean value is going to be reused, I
> think comparing it afterwards reads a little more naturally.
Agreed, fixed in v8 to copy s->data.invalidated under the spinlock and
compare it against RS_INVAL_NONE afterwards.
--
Best regards,
Shinya Kato
NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
On Tue, Jun 30, 2026 at 12:23 AM Bharath Rupireddy wrote: > My main concern is the additional proc array scan and the lock it > takes. ProcArrayLock is one of the most contended locks in production > systems with hundreds or thousands of connections. With many workers > vacuuming concurrently across hundreds of tables, I expect this extra > lock acquisition to show up in the contention path. > ComputeXidHorizons() already takes ProcArrayLock and has all the > information about who is blocking the vacuum, so I think we can > capture the blocker right there and get the reason almost for free, > without a second scan. Thank you for taking a look. Earlier versions of this patch took exactly that approach, and Sami showed it can report the wrong PID [1]. Identifying the root cause needs the complete set of procs and slots matching the final horizon, which ComputeXidHorizons() does not know until its loop has ended. On the overhead, the extra scan runs only when the log line is actually emitted (VACUUM VERBOSE, or log_autovacuum_min_duration exceeded) and only when dead tuples were in fact left unremoved. One additional LW_SHARED acquisition per logged vacuum, on top of the many ProcArrayLock acquisitions a vacuum already performs, should not be visible in the contention path. > One thing worth mentioning is that we can only ever report a > "possible" reason. There's an inherent race - by the time we report a > blocker, it may already be gone. So this is best-effort information. Agreed. The comments and the commit message state this explicitly. > The other concern is timing. The patch reports the blocker after the > vacuum has finished. With hundreds of GB of tables and indexes, where > vacuum can run for hours, reporting up front is far more useful than > learning at the end that vacuum couldn't remove the tuples. If we > capture the blocker when ComputeXidHorizons() computes the horizon, we > can tell the user early, while there's still a chance to act on it. Whether the blocker is worth reporting is only known after the heap scan, since it depends on whether any dead tuples were actually left unremovable. For seeing the blocker while a long vacuum is still running, I think a live view (for example pg_stat_progress_vacuum or a SQL-callable function) fits better than a log line. The 0001 patch keeps the infrastructure independent of vacuum so that such a view can be built on it as a follow-up, which Sami also suggested in [1]. > I wrote a patch on the same idea about a month ago, then got busy and > only noticed this thread now. If it helps, I'm happy to post it. Please feel free to post it. -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
Rebased the patches, as v8 no longer applied cleanly on the latest master. The rebased v9 patches are attached. Also, in my earlier reply to Bharath I referred to [1] but forgot to include the reference itself, so I am adding it here. [1] https://www.postgresql.org/message-id/CAA5RZ0sjMgMo4Xg-niyyF-CpkQ_CK6uOfNKYT%3D9RmiBkAxQkbQ%40mail.gmail.com -- Best regards, Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
On Wed, Jun 3, 2026 at 10:24 AM Shinya Kato wrote: > On Wed, Jun 3, 2026 at 10:05 AM Scott Ray wrote: > > I've been working on a view like this. It shows the horizon > > contribution for each backend, prepared xact, replication slot, and > > HSF walsender, broken down by class. It also shows - for each > > contributor - how the horizon would shift if that holder were > > removed. > > > > Shinya said [1] that we could have a view in the future. We could > > have both the logging and the view call a single function that reads > > the procArray and other sources to gather the horizon information. I > > think the logging and the view would complement each other. > > > > Should I start another thread? > > My mild preference would be to keep the discussion on this thread, > since the shared function design is central to both the log and the > view and may be easier to keep aligned in one place. That said, I'm > not strongly attached to that, so please pick whichever feels more > convenient. I posted a patch for the view: https://www.postgresql.org/message-id/AT-erSWn0vFw8TYLb84jqyfxgTV21gjwEo4YJDcses8qWtDkQK_pS6g2OIfVh4-L1PPn94w8-tE1mHZactVAgxPJ8vL96MXsyAnUg2Xz-Ks=@scottray.io I thought that posting the full patch here might confuse cfbot, so I decided to create a new thread and CF entry. -- Scott Ray
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Jacob Champion <jacob.champion@enterprisedb.com>
Дата:
On Sat, Jul 11, 2026 at 5:52 PM Scott Ray wrote: > I thought that posting the full patch here might confuse cfbot, so I > decided to create a new thread and CF entry. (I think the current convention is to name the patch file(s) with a `nocfbot-` prefix, and then it'll be ignored.) --Jacob
Re: Report oldest xmin source when autovacuum cannot remove tuples
Hi, On Tue, Jul 7, 2026 at 9:17 AM Shinya Kato wrote: > > On Tue, Jun 30, 2026 at 12:23 AM Bharath Rupireddy > wrote: > > My main concern is the additional proc array scan and the lock it > > takes. ProcArrayLock is one of the most contended locks in production > > systems with hundreds or thousands of connections. With many workers > > vacuuming concurrently across hundreds of tables, I expect this extra > > lock acquisition to show up in the contention path. > > ComputeXidHorizons() already takes ProcArrayLock and has all the > > information about who is blocking the vacuum, so I think we can > > capture the blocker right there and get the reason almost for free, > > without a second scan. > > Thank you for taking a look. Earlier versions of this patch took > exactly that approach, and Sami showed it can report the wrong PID > [1]. Identifying the root cause needs the complete set of procs and > slots matching the final horizon, which ComputeXidHorizons() does not > know until its loop has ended. > > On the overhead, the extra scan runs only when the log line is > actually emitted (VACUUM VERBOSE, or log_autovacuum_min_duration > exceeded) and only when dead tuples were in fact left unremoved. One > additional LW_SHARED acquisition per logged vacuum, on top of the many > ProcArrayLock acquisitions a vacuum already performs, should not be > visible in the contention path. > > > The other concern is timing. The patch reports the blocker after the > > vacuum has finished. With hundreds of GB of tables and indexes, where > > vacuum can run for hours, reporting up front is far more useful than > > learning at the end that vacuum couldn't remove the tuples. If we > > capture the blocker when ComputeXidHorizons() computes the horizon, we > > can tell the user early, while there's still a chance to act on it. > > Whether the blocker is worth reporting is only known after the heap > scan, since it depends on whether any dead tuples were actually left > unremovable. For seeing the blocker while a long vacuum is still > running, I think a live view (for example pg_stat_progress_vacuum or a > SQL-callable function) fits better than a log line. The 0001 patch > keeps the infrastructure independent of vacuum so that such a view can > be built on it as a follow-up, which Sami also suggested in [1]. > > > I wrote a patch on the same idea about a month ago, then got busy and > > only noticed this thread now. If it helps, I'm happy to post it. > > Please feel free to post it. Sorry for the delay, I spent time on this. Thank you Shinya-san for the off-list chat. When VACUUM runs for minutes to hours on large tables, this information is genuinely useful. Today, it is difficult to tell what is keeping the oldest xmin horizon from advancing until it is already held back to an unsafe degree, and even then VACUUM only warns that the cutoff for removing and freezing tuples is far in the past and lists the general possibilities (open transactions, prepared transactions, replication slots), without naming what is actually responsible. As a result, a long-running VACUUM can pass without the user getting a chance to act in time, and afterwards there is no record of why it could not prune XIDs or clean up bloat, which makes it hard to answer customer questions as basic as "what exactly held the database's VACUUM back?". The way I think about approaching this problem is: 1/ we can only ever report a possible cause, whether we capture it at the start or reconstruct it at the end with a separate scan, since a transaction or slot holding the xmin back may go away right after; given that it is best-effort either way, I would rather report it as soon as VACUUM computes its cutoffs, where it is most useful, so the user can act while the VACUUM is still running and fix things for the next relation in the same cycle or the next cycle, rather than learn at the end that the run achieved nothing, 2/ the reporting stays cheap and adds no contention on hot locks such as ProcArrayLock, and 3/ it carries the minimum actionable detail, namely the backend PID for a running transaction, the GID for a prepared transaction, the slot name for a replication slot, and the walsender PID for standby feedback. With this context, I attached two patches. 0001 reports the category of the blocker (running transaction, prepared transaction, standby feedback, replication slot, logical replication slot). It is computed inside ComputeXidHorizons(), which already holds ProcArrayLock, so there is no extra lock and no additional scan, and it is exposed in pg_stat_progress_vacuum, in VACUUM (VERBOSE) and in the autovacuum log when the run exceeds log_autovacuum_min_duration, and as extra detail on the "far in the past" warning. 0002 adds the specific identity (backend PID, prepared-xact GID, or slot name) to that warning only. Finding the identity needs TwoPhaseStateLock or ReplicationSlotControlLock, so it is done only for the warning and not for routine progress reporting. We already seem to have agreement on capturing the blocker during ComputeXidHorizons() [1] [2]. [1] https://www.postgresql.org/message-id/3bnBUxwx2npXqvHL0trI11LOOvzQ7LI0GzWqbaj5SJnk7DTb1uzStGveKwj0JJmBW4ebzGIF3az7of4I4rQeaO_PRqDnnClCduPyjM6gPgM%3D%40scottray.io [2] https://www.postgresql.org/message-id/CAOYmi%2BmKfzcj%3DGbtDhyu49kGwoN5811FqPzFfgvS7R6mzVs4aQ%40mail.gmail.com Thoughts? -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> The way I think about approaching this problem is: 1/ we can only ever > report a possible cause, whether we capture it at the start or > reconstruct it at the end with a separate scan, since a transaction or > slot holding the xmin back may go away right after; given that it is > best-effort either way, I would rather report it as soon as VACUUM > computes its cutoffs, where it is most useful, so the user can act > while the VACUUM is still running and fix things for the next relation > in the same cycle or the next cycle, rather than learn at the end that > the run achieved nothing, 2/ the reporting stays cheap and adds no > contention on hot locks such as ProcArrayLock, and 3/ it carries the > minimum actionable detail, namely the backend PID for a running > transaction, the GID for a prepared transaction, the slot name for a > replication slot, and the walsender PID for standby feedback. I have not looked at v1-, but I am wondering why don't we detach this logging from the per-table vacuum logs as an alternative? Meaning that we log the oldest blocker every X amount of time (i.e. 1 minute) if the horizon has not advanced and the same blocker persists? This can be tracked by the autovacuum launcher which will be responsible for emitting this info. I think this is better because we are no longer just emitting this information when autovacuum logging is enabled, which to me is still quite a real limitation of per-table logging. If I have many tables with quick vacuums that are getting blocked, I have to set autovacuum logging quite aggressively to get any information, even though dead tuples are piling up. Also, we don't need to compute the blocker for every table, which will just be the same for every table, most of the time. Additionally, monitoring tools only need to watch for a single recurring log line, rather than parsing per-table vacuum output. We can keep the infrastructure separate from ComputeXidHorizons as we have done in v9-0001. Since the check is throttled (at most once per minute), the concern about ProcArrayLock contention is effectively eliminated. -- Sami Imseih Amazon Web Services (AWS)
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
Hi
> +static const char *const OldestXminBlockerNames[] = {
> + [OLDEST_XMIN_BLOCKER_NONE] = "none",
> + [OLDEST_XMIN_BLOCKER_RUNNING_XACT] = "running transaction",
> + [OLDEST_XMIN_BLOCKER_PREPARED_XACT] = "prepared transaction",
> + [OLDEST_XMIN_BLOCKER_STANDBY_FEEDBACK] = "standby feedback",
> + [OLDEST_XMIN_BLOCKER_REPLICATION_SLOT] = "replication slot",
> + [OLDEST_XMIN_BLOCKER_LOGICAL_SLOT] = "logical replication slot",
No distinction was made between idle transactions and long-running transactions.It is very important to distinguish between them, as this is extremely helpful in guiding DBAs to identify the source of a OldestXminBlocker.
Thanks
Re: Report oldest xmin source when autovacuum cannot remove tuples
On Monday, July 13th, 2026 at 8:06 AM, Jacob Champion wrote: > (I think the current convention is to name the patch file(s) with a > `nocfbot-` prefix, and then it'll be ignored.) Thanks for the tip. -- Scott Ray
Re: Report oldest xmin source when autovacuum cannot remove tuples
I presented this patch at PostgreSQL Developer Meeting [1], an offline event in Japan, and Fujii-san gave me the following comments. 1. If the blocker is looked up right after the cutoff is computed, one extra scan is enough. 2. Information that needs a second lookup, such as the active versus idle state and the prepared transaction GID, is out of scope for this patch and should come as a follow-up. 3. Do not widen the scope of the patch. v10 addresses all three. 1. My previous message proposed scanning twice, right after the cutoff and again when the log line is emitted, to keep the line accurate. As Fujii-san says, the scan right after the cutoff is enough. The process named in the line may already be gone by the time the line is written, but that is true of the other values in the VACUUM log as well. So v10 scans the ProcArray and the replication slots once, right after the cutoffs are computed and only for an instrumented vacuum, keeps the blocker, and prints it when the log line is emitted: ``` tuples: 0 removed, 20000 remain, 20000 are dead but not yet removable removable cutoff: 695, which was 2 XIDs old when operation ended removable cutoff was held back by: prepared transaction ``` 2. Fixed as suggested. The line v10 prints is a simple one, and I plan to report more useful detail in follow-up patches, including Scott's comments [2]. 3. Bharath's WARNING line and pg_stat_progress_vacuum column [3] may well be useful, but I would like to keep them out of scope for now. Other changes from v9: - The log line now says "removable cutoff was held back by". "oldest xmin" is not a term the user-facing output uses, and VACUUM already calls this value the removable cutoff on the line above. - The replication slot name is now copied while ReplicationSlotControlLock is held, which closes the race Scott reported [2]. - Slots are reported by name whatever their type. v9 reported a slot that is not tied to a database and is held by some process as hot standby feedback, so a subscriber with retain_dead_tuples and no standby at all was told hot standby feedback and given the pid of the logical replication launcher holding pg_conflict_detection. - Comment cleanup. - Removed the serializable test, which duplicated another test case. The patch is attached. Thoughts? [1] https://speakerdeck.com/shinyakato_/postgresql-improve-vacuum-log-en [2] https://www.postgresql.org/message-id/o8gz3Yoq3LmnoO9oeF_3pPSlndgQmosyYKAFkiVZ60HyiA_g8cDQVs8AMkSJBRrz0-nclaPVJ2c0ilGyi3TIuAqNqjjOYzLIaJa5V65tZDg%3D%40scottray.io [3] https://www.postgresql.org/message-id/CALj2ACWaCpesxSupvN1ZpdQ1oRDdu8YvXg5-zeLFqY6zqofVGA%40mail.gmail.com -- Shinya Kato NTT OSS Center
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
Hi Shinya
Thanks for the updated v10 patch. The refactoring around GetXidHorizonBlocker()
and the prioritization of xid owner over xmin holder are very clean.
However, I would like to advocate strongly for keeping the distinction between
active and idle-in-transaction sessions (which was present in earlier versions
but dropped in v10).
From a production operations and DBA perspective, long-running idle-in-transaction
sessions (e.g. applications using ORMs or connection pools that execute a SELECT
with autocommit disabled, and then failing to commit/rollback before returning the
connection) are among the most common root causes of table bloat and horizon freeze.
While normal OLTP sessions switch rapidly between active and idle, leaked
transactions that hold back autovacuum are NOT rapidly changing—they typically
remain stagnant in "idle in transaction" for hours or days.
Reporting merely:
"removable cutoff was held back by: transaction holding snapshot (pid = %d)"
leaves DBAs without critical actionable information once the session has
disconnected:
1. If it was active, the action is SQL/index optimization or offloading heavy
queries to a standby.
2. If it was idle in transaction, the action is addressing application-side
bugs (uncommitted transaction leaks) or configuring
idle_in_transaction_session_timeout.
To avoid the layering concern of querying pgstat from procarray.c, could we
simply check proc->wait_event_info directly from PGPROC?
A backend waiting on WAIT_EVENT_CLIENT_READ while holding an open transaction/snapshot
is effectively idle-in-transaction. We could add a simple boolean flag (e.g. `is_idle`)
to XidHorizonBlocker, avoiding enum explosion while preserving this vital diagnostic clue
in the log.
What do you think?
Thanks for the updated v10 patch. The refactoring around GetXidHorizonBlocker()
and the prioritization of xid owner over xmin holder are very clean.
However, I would like to advocate strongly for keeping the distinction between
active and idle-in-transaction sessions (which was present in earlier versions
but dropped in v10).
From a production operations and DBA perspective, long-running idle-in-transaction
sessions (e.g. applications using ORMs or connection pools that execute a SELECT
with autocommit disabled, and then failing to commit/rollback before returning the
connection) are among the most common root causes of table bloat and horizon freeze.
While normal OLTP sessions switch rapidly between active and idle, leaked
transactions that hold back autovacuum are NOT rapidly changing—they typically
remain stagnant in "idle in transaction" for hours or days.
Reporting merely:
"removable cutoff was held back by: transaction holding snapshot (pid = %d)"
leaves DBAs without critical actionable information once the session has
disconnected:
1. If it was active, the action is SQL/index optimization or offloading heavy
queries to a standby.
2. If it was idle in transaction, the action is addressing application-side
bugs (uncommitted transaction leaks) or configuring
idle_in_transaction_session_timeout.
To avoid the layering concern of querying pgstat from procarray.c, could we
simply check proc->wait_event_info directly from PGPROC?
A backend waiting on WAIT_EVENT_CLIENT_READ while holding an open transaction/snapshot
is effectively idle-in-transaction. We could add a simple boolean flag (e.g. `is_idle`)
to XidHorizonBlocker, avoiding enum explosion while preserving this vital diagnostic clue
in the log.
What do you think?
Thanks
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
On Fri, Oct 2, 2026 at 3:20 PM wenhui qiu wrote: > However, I would like to advocate strongly for keeping the distinction between > active and idle-in-transaction sessions (which was present in earlier versions > but dropped in v10). Thanks for the review. Reporting the active versus idle state is out of scope for this patch, as Fujii-san suggested. I plan to address it in a follow-up patch.
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Thu, Oct 1, 2026 at 5:20 AM Shinya Kato wrote: > > I presented this patch at PostgreSQL Developer Meeting [1], an offline > event in Japan, and Fujii-san gave me the following comments. > > 1. If the blocker is looked up right after the cutoff is computed, one > extra scan is enough. > 2. Information that needs a second lookup, such as the active versus > idle state and the prepared transaction GID, is out of scope for this > patch and should come as a follow-up. > 3. Do not widen the scope of the patch. > > v10 addresses all three. Thanks for the updated patch. Sorry for the delay. I have been thinking about how useful reporting the per-vacuum blocker will be with the pg_xmin_horizon view proposed in the other thread. Why can't users find the blockers with the view and the removable cutoff that is already reported in the verbose log output? Maybe we want this for historical purposes (?). IMHO, a separate proc array scan is not the way to go for a couple of reasons. It may not report the reason that was factored into the cutoff when it was computed, and it may not be optimal to do another proc array and slot scan with their locks in the vacuum path. Thoughts? -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Maxim Orlov <orlovmg@gmail.com>
Дата:
On Thu, 1 Oct 2026 at 15:21, Shinya Kato <shinya11.kato@gmail.com> wrote:
v10 addresses all three.
Thank you for working!
I frequently work with clusters that have a large number of connections.
For this reason, I would like to raise a concern, perhaps small, but
significant to me. The XidHorizonBlocker struct contains a
name[NAMEDATALEN] field; when multiplied by the number of connections,
this can result in a substantial. All just so that, later on, we can
For this reason, I would like to raise a concern, perhaps small, but
significant to me. The XidHorizonBlocker struct contains a
name[NAMEDATALEN] field; when multiplied by the number of connections,
this can result in a substantial. All just so that, later on, we can
identify the "best" entry within that array.
But what if we try to find the "best" one while iterating through the loop?
I think that would be more optimal. Looks like this topic has already been
discussed before.
On Tue, 17 Nov 2026 at 01:05, Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote:
Thanks for the updated patch. Sorry for the delay. I have been
thinking about how useful reporting the per-vacuum blocker will be
with the pg_xmin_horizon view proposed in the other thread. Why can't
users find the blockers with the view and the removable cutoff that is
already reported in the verbose log output?
That's interesting. BTW, I do not see the pg_xmin_horizon patch CF entry.
I like the idea of being able to know what is blocking VACUUM, and the
proposed patch caught my interest. My concern, however, is also in the
need to iterate through the proc array multiple times. In my case, and I
have to deal with a very large number of connections, so that would
likely become an issue. OK, maybe not an issue, but slow things down
proposed patch caught my interest. My concern, however, is also in the
need to iterate through the proc array multiple times. In my case, and I
have to deal with a very large number of connections, so that would
likely become an issue. OK, maybe not an issue, but slow things down
a bit.
As far as descusson goes, it looks like Fujii gives his approval on one
extra pgproc scan, does he? It would be great if he could also clarify
his position on the matter, if possible, especially in light of the
introduced pg_xmin_horizon patch.
Best regards,
Maxim Orlov.
Re: Report oldest xmin source when autovacuum cannot remove tuples
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Wed, Nov 18, 2026 at 7:03 AM Maxim Orlov wrote: > > On Tue, 17 Nov 2026 at 01:05, Bharath Rupireddy wrote: >> >> Thanks for the updated patch. Sorry for the delay. I have been >> thinking about how useful reporting the per-vacuum blocker will be >> with the pg_xmin_horizon view proposed in the other thread. Why can't >> users find the blockers with the view and the removable cutoff that is >> already reported in the verbose log output? > > That's interesting. BTW, I do not see the pg_xmin_horizon patch CF entry. Thanks for taking a look. Here it is https://commitfest.postgresql.org/patch/7004 (in the Current CF). -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com