Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

Поиск
Список
Период
Сортировка
Искать

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Вложения:
Hi,

On Fri, Sep 11, 2026 at 5:40 PM Bharath Rupireddy
 wrote:
>
> I plan to review the v6 patch soon.

I reviewed the v6 patch and here are some comments. Apologies if some
of these have already been discussed. Feel free to point me to the
related discussions on any of these. I haven't reviewed the tests yet.
I will do so after the code-related comments are addressed.

1/ Good catch, and the new wording looks right. datfrozenxid can end
up older than the oldest relfrozenxid in the database, because the
computation starts from the oldest xid vacuum is allowed to remove,
not from the tables. I recommend proposing this separately and
probably back-patch it, but fine to keep it here too.

     aggressive VACUUM).  Similarly, the
     datfrozenxid column of a database's
     pg_database row is a lower bound on the
unfrozen XIDs
-    appearing in that database — it is just the minimum of the
-    per-table relfrozenxid values within
the database.
+    appearing in that database — it is no newer than, and normally
+    equal to, the minimum of the per-table
+    relfrozenxid values within the database.

2/ In both of the following places, can we have a sample query and
output with all the per-class rows present? IMO, that works better and
readily usable for those looking at it.

+       including rows for backends in other databases.  Sort all rows by
+       age(shared_xmin) descending
+       to find the oldest pinners.  Use NULLS LAST, because
+       a row with a null shared_xmin pins
+       nothing.

+   To find the row binding a horizon class, order the applicable rows by
+   descending age() of the class column, placing
+   null values last.
+   xid has no ordering operators, so
+   age() serves as the wraparound-safe sort key.

3/ A few wording nits, mostly about matching what the docs already
say. The steps that follow say "old prepared transactions",
"long-running open transactions" and "old replication slots".
system-views.sgml says "backend currently holding a snapshot or
transaction ID". monitoring.sgml calls this the xmin horizon, and
describes the fourth kind as a standby's xmin horizon reported by
hot_standby_feedback, written without hyphens as the docs do
everywhere. And for shared, the docs' usual phrase is shared catalogs.

How about changing "snapshot-holding backend" to "backend holding a
snapshot or transaction ID", "per-class xmin contribution" to the
column names shared_xmin, catalog_xmin and data_xmin (or to xmin
horizons), "hot-standby-feedback sender" to "hot standby feedback
sender", and "cluster-wide shared horizon" to the horizon for shared
catalogs? Same comments applicable elsewhere in the patch.

+      Identify the source.  Query
+       pg_xmin_horizon,
+       which reports one row per snapshot-holding backend, replication slot,
+       prepared transaction, or hot-standby-feedback sender with each row's
+       per-class xmin contribution.  The warning
+       is driven by the database's datfrozenxid,
+       which can never advance past the cluster-wide shared horizon, and
+       every row's shared_xmin feeds that horizon,
+       including rows for backends in other databases.  Sort all rows by
+       age(shared_xmin) descending
+       to find the oldest pinners.  Use NULLS LAST, because

4/ The steps for finding the cause of the wraparound warnings
currently point at pg_stat_activity, pg_prepared_xacts and
pg_replication_slots, and the patch replaces those with the new view.
The intent makes sense, since the whole point of pg_xmin_horizon is to
be the first place to look. But the existing methods are not wrong
either, and there are scripts and runbooks built around them. So how
about mentioning both, something like "You can find these in
pg_xmin_horizon or existing views"? There will be no surprises for
those relying on the existing views, and they can move to the new one
if they wish.

-      End long-running open transactions. You can find these
by checking
-       pg_stat_activity
for rows where
-       age(backend_xid) or
age(backend_xmin) is
-       large. Such transactions should be committed or rolled back,
or the session
-       can be terminated using
pg_terminate_backend.

+      End long-running open transactions by committing, rolling back,
+       or terminating the session using
+       pg_terminate_backend.
+     
+     

5/ How about "sources holding back the cluster's xmin horizon,
preventing VACUUM from removing dead row versions and clearing old
XIDs"? Matches what monitoring.sgml and maintenance.sgml say. Same
comment applies to the other places in the patch that say removal
horizon.

+     
+      pg_xmin_horizon
+      sources holding back the cluster's VACUUM removal horizon
+     

+   and reports each row's raw per-class xmin
+   contributions to the cluster's VACUUM removal horizon.
+   A row whose per-class xmin columns are all
+   null does not currently pin the horizon.

6/ "physical-replication sender" is a new word here, and calling it a
sender is confusing when what it holds is an xmin the standby sent to
it. How about "a standby_feedback row represents a WAL sender process
without a replication slot, holding the xmin horizon sent by its
standby through hot_standby_feedback"?

+       The row's kind: backend,
+       replication_slot, prepared_xact,
+       or standby_feedback.  A
+       standby_feedback row represents a
physical-replication
+       sender propagating hot_standby_feedback
+       without a replication slot.  A sender that does use a slot is reported
+       through that slot's replication_slot row instead.

7/ Why join with pg_prepared_xacts here? The point of pg_xmin_horizon
was to collect most of the things in C to avoid joining existing
views. The join also means gid reads null if the prepared transaction
ends in between, for a row the view still reports. Why not return gid
from the function itself, same as xact_start?

+    FROM pg_get_xmin_horizon() c
+        LEFT JOIN pg_prepared_xacts p
+            ON c.kind = 'prepared_xact' AND p.transaction = c.xid

+       gid text
+      
+      
+       The global transaction identifier for prepared_xact
+       rows, joined in from
+       pg_prepared_xacts.
+       Null for all other kinds.
+      
+      

8/ How about using "replication_slot and
standby_feedback rows pin the horizon ..."?

+       Slot and standby_feedback rows pin the horizon
+       cluster-wide regardless of

9/ This seems unnecessary. The previous sentence already says these
rows pin cluster-wide regardless of datid, so the note about filtering
on datid adds little.

+       datid, and a query filtering
+       by datid will exclude them.
+      

10/ "The transaction ID this row owns, or null if it owns none" reads
a bit confusing. How about "Transaction identifier of this row's
source, if any; see " similar to
pg_stat_activity.backend_xid?

+      
+       xid xid
+      
+      
+       The transaction ID this row owns, or null if it owns none; see
+       .  For

11/ How about listing all the columns here, shared_xmin, catalog_xmin
and data_xmin, for clarity?

+       standby_feedback rows.  A row with a null
+       xid can still pin the horizon through
+       the *_xmin columns.

12/ Same point as the per-class one above. How about "The transaction
ID this row pins for the shared xmin horizon. Null if it does not pin
that horizon", and likewise for catalog_xmin and data_xmin? The
data_xmin entry then reads "pins none of the three horizons and shows
null in shared_xmin, catalog_xmin and data_xmin".

+     
+      
+       shared_xmin xid
+      
+      
+       The transaction ID this row pins for the shared horizon class.
+       Null if it does not pin that class.
+      
+     

13/ How about following the existing columns here, something like
"Time when this row's transaction was started, or, for prepared_xact
rows, the time at which the transaction was prepared for commit",
similar to pg_stat_activity.xact_start and pg_prepared_xacts.prepared?

+     
+      
+       xact_start timestamptz
+      
+      
+       Time when the row's transaction was started, or, for
+       prepared_xact rows, when the transaction was
+       prepared.  Null for replication_slot rows,
+       standby_feedback rows, and
+       backend rows belonging to walsender processes.
+      
+     

14/ This paragraph took me a couple of passes to follow although I
understand how these contribute to overall XID horizon in
ComputeXidHorizons().  How about something shorter, in the order of
what a reader needs?

For replication_slot rows, shared_xmin and catalog_xmin report the
older of the slot's xmin and catalog_xmin, while data_xmin reports the
slot's xmin alone, because a slot's catalog_xmin applies to catalog
rows only, not to dead row versions in user tables. These are the
slot's effective xmins (the values the server uses when it computes
the horizon), so while a slot is being created they can briefly differ
from the ones shown in pg_replication_slots. The server also keeps a
single oldest value across all slots, recomputed only when a slot
changes, so for a short while it can be older than every value shown
here, and a horizon can be held back by a value that no row reports.
An invalidated slot holds back nothing and reports null in all three
columns.

+  
+   For replication_slot rows,
+   shared_xmin and
+   catalog_xmin both report the older of the
+   slot's xmin and
+   catalog_xmin.  The
+   data_xmin column reports the slot's

15/ This one is hard to follow. How about a short example query
instead of describing the sort in prose, as in comment 3, and
splitting the rest so each paragraph does one thing?

To find the row holding back an xmin horizon, use a query such as:
<< query here >>
xid has no ordering operators, so the sort uses age(), which is
wraparound-safe. Which rows apply depends on the column and on datid,
as described above.

When several rows report the same oldest value, that xmin horizon
cannot advance until all of them release it, so resolving only one of
them has no effect. If one of those rows has an xid equal to that
value, the horizon has to wait for that transaction to finish.

When no row reports a value for an xmin horizon, it advances on its
own to a point just past the newest completed transaction, which this
view does not show. Note also that backend rows and replication slot
rows are gathered at slightly different times, so a single query is
not a snapshot of the whole cluster at one instant. See  for the steps to take when an xmin
horizon is held back.

+  
+   To find the row binding a horizon class, order the applicable rows by
+   descending age() of the class column, placing
+   null values last.
+   xid has no ordering operators, so

16/ How about "Querying pg_xmin_horizon on a standby is not supported
and raises an error, because the view cannot report the primary's
running transactions during recovery"?

+   
+    Querying pg_xmin_horizon on a hot standby is not
+    supported and will raise an error.
+   

17/ How about defining a macro for this flag test similar to PROC_*
and using it in all three places, instead of a comment asking future
authors to keep them in sync?

-                * decoding (which manages xmin separately, check below).
+                * decoding (which manages xmin separately, check
below).  Keep this
+                * filter in sync with pg_get_xmin_horizon()'s classifier.
                 */
                if (statusFlags & (PROC_IN_VACUUM | PROC_IN_LOGICAL_DECODING))
                        continue;

18/ GetXidHorizonProcs() acquires ProcArrayLock once and gathers all
procs in a single pass, whereas pg_stat_activity takes the lock once
per backend, so each snapshot does N acquisitions and releases. I
measured this by keeping ~500 backends connected with pgbench, then
running each view repeatedly from one backend while a separate
4-client pgbench write workload ran alongside. Query exec time is
0.304 ms vs 1.335 ms for pg_xmin_horizon and pg_stat_activity
respectively (4.4x), and the write workload TPS reduces by 11.7% vs
27.4%. Connection latency is also lower since connection setup takes
the lock exclusive, measuring 2.21 ms with no polling, 2.55 ms with
pg_xmin_horizon polling, and 3.09 ms with pg_stat_activity polling.

19/ The comment mostly says what the exact code does incl. variable
names, and the one thing it adds, that the rows are mutually
consistent, is not what the shared lock gives. How about the
following?

/*
 * Get the xid, xmin and other horizon inputs of every proc, in one pass over
 * the proc array.
 *
 * These are the same per-proc inputs that ComputeXidHorizons() uses. Processes
 * cannot enter or leave the array during the pass, but a process can install a
 * new xmin or get an xid while the pass is still running, see
 * GetSnapshotData() and GetNewTransactionId(), so the values returned can be
 * from different moments.
 *
 * There is a race here. The lock is released before returning, so by the time
 * the caller reads an entry the process may have ended its transaction or
 * exited altogether.
 *
 * The caller is responsible for freeing the returned array.
 */

20/ How about returning both the array and its length as out
parameters, void GetXidHorizonProcs(XidHorizonProc **procs, int
*nprocs)?

21/ The count variable looks redundant. Nothing is skipped in the
loop, so count always ends up equal to arrayP->numProcs, which could
be used directly.

22/ With pgstat_get_beentry_by_proc_number(), the new function is not
needed unless I'm missing something else. It does the change count
retry internally, so something like the following is enough.

PgBackendStatus *beentry = pgstat_get_beentry_by_proc_number(p->procNumber);

if (beentry != NULL && beentry->st_procpid == pid &&
beentry->st_backendType != B_WAL_SENDER)
r->xact_start = beentry->st_xact_start_timestamp;

23/ Nit: How about using consistent wording here?
int pid; /* Backend's process ID; 0 if prepared xact */
int procNumber; /* ProcNumber, which is also the
* BackendStatusArray index; not valid for
* prepared xact dummy procs */
24/ Nit: proisstrict has no effect for a function with no arguments,
and pg_get_aios(), pg_lock_status() and pg_prepared_xact() all leave
it out. How about dropping it? The descr could also read like its
neighbours, something such as 'information about sources holding back
the cluster's xmin horizons'.

+{ oid => '8054',
+  descr => 'per-source inputs to the cluster xmin horizons',
+  proname => 'pg_get_xmin_horizon', prorows => '100', proisstrict => 'f',
+  proretset => 't', provolatile => 'v', proparallel => 'r',
prorettype => 'record',
+  proargtypes => '',
+  proallargtypes => '{text,int4,name,oid,xid,xid,xid,xid,timestamptz}',
+  proargmodes => '{o,o,o,o,o,o,o,o,o}',
+  proargnames =>
'{kind,pid,slot_name,datid,xid,shared_xmin,catalog_xmin,data_xmin,xact_start}',
+  prosrc => 'pg_get_xmin_horizon', proacl =>
'{POSTGRES=X,pg_read_all_stats=X}' },

25/ How about merging the second and third passes in
pg_get_xmin_horizon(), something like the attached diff on top of v6?
Emitting rows while holding ReplicationSlotControlLock seems okay, the
same way pg_get_replication_slots() already does it. Is there a reason
not to do this?

26/ Nit: How about something like the following to be clearer?

 * procarrayfuncs.c
 *  SQL-callable functions related to POSTGRES process array code.
 *

27/ For a parallel query, and for concurrent REPACK with decoding
workers, the leader and every worker gets its own pinning row. Nothing
in the view itself links a worker row back to its leader, though
joining pg_stat_activity on pid gives leader_pid for anyone who wants
it. How about a doc note saying so?

28/ Decoding through pg_logical_slot_get_changes() shows up as an
ordinary backend row with an xmin of its own, which is worth knowing
for anyone looking at what holds the horizon back. How about a doc
note saying so?

29/ The note in the docs about a backend running VACUUM showing null
in shared_xmin, catalog_xmin and data_xmin holds only for lazy VACUUM,
which is the one path that sets PROC_IN_VACUUM. VACUUM FULL and
CLUSTER report an xid and all three xmins, and ANALYZE reports all
three xmins with a null xid. How about clarifying this in the docs?

statement xid shared_xmin catalog_xmin data_xmin
lazy VACUUM null null, null, null
VACUUM FULL 668 668, 668, 668
CLUSTER 681 681, 681, 681
ANALYZE null 681, 681, 681

Thanks for reading this far.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Bharath,

Thanks for the measurements.  I raised the single-pass point earlier but without numbers, so it's good to see it quantified.

Regarding your point 22, pgstat_get_beentry_by_proc_number() calls pgstat_get_local_beentry_by_proc_number(), which calls pgstat_read_current_status() and then searches localBackendStatusTable,
so it reads the cached per-transaction snapshot rather than BackendStatusArray.  
Two consequences: the xact_start value would again come from a snapshot that can predate the procarray pass by an arbitrary
amount, which is what I asked Scott to fix and why the new helper reads the array directly. And building that snapshot is the loop that takes
ProcArrayLock once per active backend, which is the cost your point 18 measures.

The change-count retry does happen, but only while the snapshot is being built.  After that the caller is reading a local copy, so it doesn't buy freshness.

Regards,
Surya Poondla

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Hi Scott,

Thanks for working on this.

When reviewing the "Report oldest xmin source ..." thread [1], I began to
wonder whether this information would be better exposed through a view
rather than only through logging.  I think exposing this information through
a view is the right direction.

Logging has benefits, but a view gives a DBA an opportunity to identify and
resolve the problem before allowing a VACUUM to complete without doing useful
cleanup.

I realize that the patch is already at v6 and that a fair amount of work has
gone into the current approach.  However, since this introduces a new system
view, I think it is worth considering the user-facing design a bit more.

Looking at v6, I am not sure that one row per potential horizon input is the
most useful representation, especially if a DBA must construct a potentially
complex query before getting an actionable answer. The questions a DBA needs
answered by this view are:

1/ Which horizon is being held back, and at what XID?

2/ What is currently holding it back?

3/ What action can be taken to allow it to advance?

The view contains the raw information needed to answer these questions, but
leaves the DBA to reconstruct the effective horizons in SQL.  I think the
view should do that itself.

The first issue I see is that pg_get_xmin_horizon() does not use
ComputeXidHorizons(), even though that is where the horizons used by VACUUM
are calculated.  Instead, it exposes a separately gathered set of per-source
inputs.

The following comment added to ComputeXidHorizons() makes this coupling
explicit:

@@ -1765,7 +1765,8 @@ ComputeXidHorizons(ComputeXidHorizonsResult *h)
  /*
  * Skip over backends either vacuuming (which is ok with rows being
  * removed, as long as pg_subtrans is not truncated) or doing logical
- * decoding (which manages xmin separately, check below).
+ * decoding (which manages xmin separately, check below).  Keep this
+ * filter in sync with pg_get_xmin_horizon()'s classifier.
  */

The need for this comment seems like a sign that this logic is happening at
the wrong level.  I think the underlying function should expose the effective
horizons directly from ComputeXidHorizons(), along with enough information to
identify their sources.  A SQL view can then present those horizons and
determine why each one is being held back.

Perhaps something along these lines, with a stable set of rows representing
the horizons:

```
    horizon | datid | xmin | pids | slot_names | gids
```

Would it make sense to drive the view from ComputeXidHorizons() and add the
source attribution on top of those results?

[1] https://www.postgresql.org/message-id/20220211083126.2qb7ij2u6je5c5hm%40alap3.anarazel.de

--
Sami Imseih
Amazon Web Services (AWS)


Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
> When reviewing the "Report oldest xmin source ..." thread [1], I began to
> wonder whether this

Sorry. I meant to share the link below:

https://www.postgresql.org/message-id/CAA5RZ0sjMgMo4Xg-niyyF-CpkQ_CK6uOfNKYT%3D9RmiBkAxQkbQ%40mail.gmail.com

--
Sami


Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
Hi Surya,

On Thursday, September 17th, 2026 at 1:14 PM, surya poondla  wrote:

> Bharath pointed out one asymmetry already i.e pg_stat_activity shows
> pid, datid, xid and xmin to unprivileged non-owners while
> pg_xmin_horizon shows nothing, and this would be one in the other
> direction if the ACL were ever loosened or EXECUTE granted directly.
> Would it be worth applying HAS_PGSTAT_PERMISSIONS per row in the SRF?

No view in PG mixes revoke from PUBLIC with permissions checks per row.
pg_shmem_allocations, pg_backend_memory_contexts,
pg_dsm_registry_allocations, and pg_aios all use the former only.  This
patch follows that convention, sets a conservative default, and trusts
DBAs to configure access.

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:

Thanks for the review.

On Tuesday, September 15th, 2026 at 1:28 PM, Bharath Rupireddy  wrote:

> Good catch, and the new wording looks right. datfrozenxid can end
> up older than the oldest relfrozenxid in the database, because the
> computation starts from the oldest xid vacuum is allowed to remove,
> not from the tables. I recommend proposing this separately and
> probably back-patch it, but fine to keep it here too.
>
>      aggressive VACUUM).  Similarly, the
>      datfrozenxid column of a database's
>      pg_database row is a lower bound on the
> unfrozen XIDs

1. I'll keep it here.

> In both of the following places, can we have a sample query and
> output with all the per-class rows present? IMO, that works better and
> readily usable for those looking at it.

2. Examples would add little here.

> A few wording nits, mostly about matching what the docs already
> say. The steps that follow say "old prepared transactions",
> "long-running open transactions" and "old replication slots".
> system-views.sgml says "backend currently holding a snapshot or
> transaction ID". monitoring.sgml calls this the xmin horizon, and
> describes the fourth kind as a standby's xmin horizon reported by
> hot_standby_feedback, written without hyphens as the docs do
> everywhere. And for shared, the docs' usual phrase is shared catalogs.
>
> How about changing "snapshot-holding backend" to "backend holding a
> snapshot or transaction ID", "per-class xmin contribution" to the
> column names shared_xmin, catalog_xmin and data_xmin (or to xmin
> horizons), "hot-standby-feedback sender" to "hot standby feedback
> sender", and "cluster-wide shared horizon" to the horizon for shared
> catalogs? Same comments applicable elsewhere in the patch.

3. Done.

> The steps for finding the cause of the wraparound warnings
> currently point at pg_stat_activity, pg_prepared_xacts and
> pg_replication_slots, and the patch replaces those with the new view.
> The intent makes sense, since the whole point of pg_xmin_horizon is to
> be the first place to look. But the existing methods are not wrong
> either, and there are scripts and runbooks built around them. So how
> about mentioning both, something like "You can find these in
> pg_xmin_horizon or existing views"? There will be no surprises for
> those relying on the existing views, and they can move to the new one
> if they wish.

4. Existing methods are wrong.  No existing view exposes the
statusFlags ComputeXidHorizons() reads, so pg_stat_activity shows a
backend_xmin for backends the horizons skip, and the wraparound steps
treat every large backend_xmin as a pin.  As one consequence, a user
following the steps terminates a lazy VACUUM for its large
backend_xmin, though it pins nothing and freezes the old XIDs that
cause the warning.

> How about "sources holding back the cluster's xmin horizon,
> preventing VACUUM from removing dead row versions and clearing old
> XIDs"? Matches what monitoring.sgml and maintenance.sgml say. Same
> comment applies to the other places in the patch that say removal
> horizon.

5. Done.

> "physical-replication sender" is a new word here, and calling it a
> sender is confusing when what it holds is an xmin the standby sent to
> it. How about "a standby_feedback row represents a WAL sender process
> without a replication slot, holding the xmin horizon sent by its
> standby through hot_standby_feedback"?

6. Done.

> Why join with pg_prepared_xacts here? The point of pg_xmin_horizon
> was to collect most of the things in C to avoid joining existing
> views. The join also means gid reads null if the prepared transaction
> ends in between, for a row the view still reports. Why not return gid
> from the function itself, same as xact_start?

7. No, the point was not to avoid joining existing views.  The main
points were to avoid transcribing the horizon policy logic from C to
SQL and to avoid publishing implementation details in public views.
v6 replaced the pg_stat_activity join to get fresh data, not because
joins are bad.  Which locks would the function hold while it reads the
gid?  How would emitting null gids for these rows adversely impact the
user?

> How about using "replication_slot and
> standby_feedback rows pin the horizon ..."?

8. Done.

> This seems unnecessary. The previous sentence already says these
> rows pin cluster-wide regardless of datid, so the note about filtering
> on datid adds little.

9. Done.

> "The transaction ID this row owns, or null if it owns none" reads
> a bit confusing. How about "Transaction identifier of this row's
> source, if any; see " similar to
> pg_stat_activity.backend_xid?

10. Done.

> How about listing all the columns here, shared_xmin, catalog_xmin
> and data_xmin, for clarity?

11. Done.

> Same point as the per-class one above. How about "The transaction
> ID this row pins for the shared xmin horizon. Null if it does not pin
> that horizon", and likewise for catalog_xmin and data_xmin? The
> data_xmin entry then reads "pins none of the three horizons and shows
> null in shared_xmin, catalog_xmin and data_xmin".

12. Done.

> How about following the existing columns here, something like
> "Time when this row's transaction was started, or, for prepared_xact
> rows, the time at which the transaction was prepared for commit",
> similar to pg_stat_activity.xact_start and pg_prepared_xacts.prepared?

13. The replacement would say the same thing with more words.

> This paragraph took me a couple of passes to follow although I
> understand how these contribute to overall XID horizon in
> ComputeXidHorizons().  How about something shorter, in the order of
> what a reader needs?
>
> For replication_slot rows, shared_xmin and catalog_xmin report the
> older of the slot's xmin and catalog_xmin, while data_xmin reports the
> slot's xmin alone, because a slot's catalog_xmin applies to catalog
> rows only, not to dead row versions in user tables. These are the
> slot's effective xmins (the values the server uses when it computes
> the horizon), so while a slot is being created they can briefly differ
> from the ones shown in pg_replication_slots. The server also keeps a
> single oldest value across all slots, recomputed only when a slot
> changes, so for a short while it can be older than every value shown
> here, and a horizon can be held back by a value that no row reports.
> An invalidated slot holds back nothing and reports null in all three
> columns.

14. I rewrote this part.  The server keeps two combined slot values,
one for xmin and one for catalog_xmin, and they feed different horizons.

> This one is hard to follow. How about a short example query
> instead of describing the sort in prose, as in comment 3, and
> splitting the rest so each paragraph does one thing?
>
> To find the row holding back an xmin horizon, use a query such as:
> << query here >>
> xid has no ordering operators, so the sort uses age(), which is
> wraparound-safe. Which rows apply depends on the column and on datid,
> as described above.
>
> When several rows report the same oldest value, that xmin horizon
> cannot advance until all of them release it, so resolving only one of
> them has no effect. If one of those rows has an xid equal to that
> value, the horizon has to wait for that transaction to finish.
>
> When no row reports a value for an xmin horizon, it advances on its
> own to a point just past the newest completed transaction, which this
> view does not show. Note also that backend rows and replication slot
> rows are gathered at slightly different times, so a single query is
> not a snapshot of the whole cluster at one instant. See  linkend="vacuum-for-wraparound"/> for the steps to take when an xmin
> horizon is held back.

15. I split the paragraph but declined the example query for the same
reason as 2.

> How about "Querying pg_xmin_horizon on a standby is not supported
> and raises an error, because the view cannot report the primary's
> running transactions during recovery"?

16. I changed this to match other recovery restrictions like those in
func-admin.sgml.

> How about defining a macro for this flag test similar to PROC_*
> and using it in all three places, instead of a comment asking future
> authors to keep them in sync?

17. Done.

> GetXidHorizonProcs() acquires ProcArrayLock once and gathers all
> procs in a single pass, whereas pg_stat_activity takes the lock once
> per backend, so each snapshot does N acquisitions and releases. I
> measured this by keeping ~500 backends connected with pgbench, then
> running each view repeatedly from one backend while a separate
> 4-client pgbench write workload ran alongside. Query exec time is
> 0.304 ms vs 1.335 ms for pg_xmin_horizon and pg_stat_activity
> respectively (4.4x), and the write workload TPS reduces by 11.7% vs
> 27.4%. Connection latency is also lower since connection setup takes
> the lock exclusive, measuring 2.21 ms with no polling, 2.55 ms with
> pg_xmin_horizon polling, and 3.09 ms with pg_stat_activity polling.

18. Thanks.

> The comment mostly says what the exact code does incl. variable
> names, and the one thing it adds, that the rows are mutually
> consistent, is not what the shared lock gives. How about the
> following?
>
> /*
>  * Get the xid, xmin and other horizon inputs of every proc, in one pass over
>  * the proc array.
>  *
>  * These are the same per-proc inputs that ComputeXidHorizons() uses. Processes
>  * cannot enter or leave the array during the pass, but a process can install a
>  * new xmin or get an xid while the pass is still running, see
>  * GetSnapshotData() and GetNewTransactionId(), so the values returned can be
>  * from different moments.
>  *
>  * There is a race here. The lock is released before returning, so by the time
>  * the caller reads an entry the process may have ended its transaction or
>  * exited altogether.
>  *
>  * The caller is responsible for freeing the returned array.
>  */

19. I rewrote the comment.  The property that you called a "race"
applies to any function that returns data that may change later, and it
doesn't warrant a separate paragraph.

> How about returning both the array and its length as out
> parameters, void GetXidHorizonProcs(XidHorizonProc **procs, int
> *nprocs)?

20. GetXidHorizonProcs() follows the convention of
GetVirtualXIDsDelayingChkpt() and GetCurrentVirtualXIDs() in the same
file.

> The count variable looks redundant. Nothing is skipped in the
> loop, so count always ends up equal to arrayP->numProcs, which could
> be used directly.

21. Done.

> With pgstat_get_beentry_by_proc_number(), the new function is not
> needed unless I'm missing something else. It does the change count
> retry internally, so something like the following is enough.
>
> PgBackendStatus *beentry = pgstat_get_beentry_by_proc_number(p->procNumber);
>
> if (beentry != NULL && beentry->st_procpid == pid &&
> beentry->st_backendType != B_WAL_SENDER)
> r->xact_start = beentry->st_xact_start_timestamp;

22. As Surya pointed out, pgstat_get_beentry_by_proc_number() reads from
a cache, and pgstat_get_xact_start_by_proc_number() exists to read fresh
data.

> Nit: How about using consistent wording here?
> int pid; /* Backend's process ID; 0 if prepared xact */
> int procNumber; /* ProcNumber, which is also the
> * BackendStatusArray index; not valid for
> * prepared xact dummy procs */

23. Done.

> Nit: proisstrict has no effect for a function with no arguments,
> and pg_get_aios(), pg_lock_status() and pg_prepared_xact() all leave
> it out. How about dropping it? The descr could also read like its
> neighbours, something such as 'information about sources holding back
> the cluster's xmin horizons'.

24. Done.

> How about merging the second and third passes in
> pg_get_xmin_horizon(), something like the attached diff on top of v6?
> Emitting rows while holding ReplicationSlotControlLock seems okay, the
> same way pg_get_replication_slots() already does it. Is there a reason
> not to do this?

25. pg_get_xmin_horizon_build_tuple() declares 10 parameters, and 5
consecutive parameters use uint32 after resolving typedefs.  A developer
could easily pass them in the wrong order.

> Nit: How about something like the following to be clearer?
>
>  * procarrayfuncs.c
>  *  SQL-callable functions related to POSTGRES process array code.
>  *

26. I rewrote the comment to follow lockfuncs.c and waitfuncs.c.

> For a parallel query, and for concurrent REPACK with decoding
> workers, the leader and every worker gets its own pinning row. Nothing
> in the view itself links a worker row back to its leader, though
> joining pg_stat_activity on pid gives leader_pid for anyone who wants
> it. How about a doc note saying so?

27. Done.

> Decoding through pg_logical_slot_get_changes() shows up as an
> ordinary backend row with an xmin of its own, which is worth knowing
> for anyone looking at what holds the horizon back. How about a doc
> note saying so?

28. Done.

> The note in the docs about a backend running VACUUM showing null
> in shared_xmin, catalog_xmin and data_xmin holds only for lazy VACUUM,
> which is the one path that sets PROC_IN_VACUUM. VACUUM FULL and
> CLUSTER report an xid and all three xmins, and ANALYZE reports all
> three xmins with a null xid. How about clarifying this in the docs?
>
> statement xid shared_xmin catalog_xmin data_xmin
> lazy VACUUM null null, null, null
> VACUUM FULL 668 668, 668, 668
> CLUSTER 681 681, 681, 681
> ANALYZE null 681, 681, 681

29. I clarified this part.  CLUSTER needs no special mention.

The attached v7 applies to 3c5d9d914fa.

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
Hi Sami,

Thanks for the feedback.

On Thursday, September 17th, 2026 at 7:00 PM, Sami Imseih  wrote:

> The need for this comment seems like a sign that this logic is happening at
> the wrong level.

Master already tests those two flags in ComputeXidHorizons() and
GetSnapshotData().  The tree has dozens of comments that say "keep in
sync".  They mark dependencies, not misplaced logic.  v7 replaces the
test you quoted with one macro used at all three sites.  One
keep-in-sync comment remains where ComputeXidHorizons() applies the slot
xmins.

> I think the underlying function should expose the effective
> horizons directly from ComputeXidHorizons(), along with enough information to
> identify their sources.
>
>     horizon | datid | xmin | pids | slot_names | gids

ComputeXidHorizons() computes the data and catalog horizons for
MyDatabaseId only, so a view built on it shows one database per
connection.  It sees slots as two aggregate xmins and prepared
transactions as PGPROCs with pid 0, so it has no slot names or gids.
The slot array and the two-phase state hold the slot names and gids,
under their own locks, and the patch reads them there.

> The view contains the raw information needed to answer these questions, but
> leaves the DBA to reconstruct the effective horizons in SQL.

A query over the patch's rows produces the summary.  No query turns the
summary back into the rows.  Andres asked for "a view showing all the
sources of the horizon being held back" [1].  The view shows every
source and the gaps between them, which tell the user how far the
horizons could advance.

> Would it make sense to drive the view from ComputeXidHorizons() and add the
> source attribution on top of those results?

Do you mean calling ComputeXidHorizons() for the values and finding
the sources in a second pass, or changing ComputeXidHorizons() to
record them?

[1] https://wiki.postgresql.org/wiki/User:Andresfreund/Desired_Changes

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Hi,

> > The need for this comment seems like a sign that this logic is happening at
> > the wrong level.
>
> Master already tests those two flags in ComputeXidHorizons() and
> GetSnapshotData(). The tree has dozens of comments that say "keep in
> sync". They mark dependencies, not misplaced logic. v7 replaces the
> test you quoted with one macro used at all three sites. One
> keep-in-sync comment remains where ComputeXidHorizons() applies the slot
> xmins.

After thinking about this some more, I think the right level for the
shared part is the small procarray rules next to ComputeXidHorizons(),
rather than a new procarrayfuncs.c file.

The idea I have been playing with locally is to add a
ComputeXidHorizonsData() helper next to ComputeXidHorizons().  It
doesn't call ComputeXidHorizons() directly, because the reporting side
needs source attribution and all-database reporting, as you mention.
But it can share the parts that are easy to get wrong, like how we
derive the effective proc xmin from xid/xmin, and which procs don't
affect removable-tuple horizons.

So ComputeXidHorizons() stays the same, except for using those small
helpers.  ComputeXidHorizonsData() is a simpler procarray collector.  It
returns latestCompletedXid + 1, the recovery KnownAssignedXids xmin, and
PGPROC entries that can affect horizons, with their classification
(backend, prepared transaction, or standby feedback), database OID, and
effective xmin.  The SQL function can then combine that with the slot
data it already has to inspect separately to build the reported horizon
rows.  This still duplicates some slot horizon handling for now, but
avoids having the SQL-facing code independently interpret the procarray
rules.

Initially, I thought about a ComputeXidHorizonsInternal() which takes a
bool called with_horizon_data and returns the data needed by the SQL
function.  ComputeXidHorizons() would then become a wrapper for
ComputeXidHorizonsInternal() with with_horizon_data = false.  I did not
have any performance concerns with this approach, but I also no longer
like the idea of turning ComputeXidHorizons() into a multi-purpose
function.

> > The view contains the raw information needed to answer these questions, but
> > leaves the DBA to reconstruct the effective horizons in SQL.
>
> A query over the patch's rows produces the summary.  No query turns the
> summary back into the rows.  Andres asked for "a view showing all the
> sources of the horizon being held back" [1].  The view shows every
> source and the gaps between them, which tell the user how far the
> horizons could advance.

I did not read "sources" here as necessarily meaning one row per PID.  I
went digging into older conversations and found [2], where Andres lays
out a potential shape for this view, where we key every row by "datname"
and "horizon", and where the shared horizon itself is a NULL datname.

So I think we can start out with a function like this which just returns
the data for each datid/horizon, such as:


```
postgres=# select * from pg_get_vacuum_horizons();
-[ RECORD 1 ]-----------------+--------
horizon                       | shared
datid                         |
xid                           | 664
source_count                  | 2
backend_horizon               | 664
prepared_xact_horizon         |
physical_slot_horizon         |
physical_slot_catalog_horizon |
logical_slot_horizon          |
logical_slot_catalog_horizon  |
standby_feedback_horizon      |
primary_xact_horizon          |
-[ RECORD 2 ]-----------------+--------
horizon                       | catalog
datid                         | 1
xid                           | 666
...
.....
-[ RECORD 3 ]-----------------+--------
horizon                       | data
datid                         | 1
xid                           | 666
source_count                  | 0
...
.....
-[ RECORD 4 ]-----------------+--------
horizon                       | catalog
datid                         | 4
xid                           | 666
source_count                  | 0
...
.....
-[ RECORD 5 ]-----------------+--------
horizon                       | data
datid                         | 4
xid                           | 666
source_count                  | 0
...
.....
-[ RECORD 6 ]-----------------+--------
horizon                       | catalog
datid                         | 5
xid                           | 664
source_count                  | 1
backend_horizon               | 664
...
.....
-[ RECORD 7 ]-----------------+--------
horizon                       | data
datid                         | 5
xid                           | 664
source_count                  | 1
backend_horizon               | 664
...
.....
-[ RECORD 8 ]-----------------+--------
horizon                       | catalog
datid                         | 16384
xid                           | 666
source_count                  | 1
backend_horizon               | 666
...
.....
-[ RECORD 9 ]-----------------+--------
horizon                       | data
datid                         | 16384
xid                           | 666
source_count                  | 1
backend_horizon               | 666
...
.....
```

> > Would it make sense to drive the view from ComputeXidHorizons() and add the
> > source attribution on top of those results?
>
> Do you mean calling ComputeXidHorizons() for the values and finding
> the sources in a second pass, or changing ComputeXidHorizons() to
> record them?

And using the base function, we can construct a system view, or document
a way to use it with joins on other system views to come up with a view
that looks like:

```
 horizon | datname  | xid | source_count | source_type |  pid   |
slot_name | gid | source_xmin
---------+----------+-----+--------------+-------------+--------+-----------+-----+-------------
 shared  |          | 664 |            2 | backend     | 330161 |
     |     |         664
 catalog | postgres | 664 |            1 | backend     | 330161 |
     |     |         664
 catalog | db1      | 666 |            1 | backend     | 330353 |
     |     |         666
 data    | postgres | 664 |            1 | backend     | 330161 |
     |     |         664
 data    | db1      | 666 |            1 | backend     | 330353 |
     |     |         666
(5 rows)
```

horizon | datname  | xid | source_count | source_type |  pid   |
slot_name | gid | source_xmin
---------+----------+-----+--------------+-------------+--------+-----------+-----+-------------
 shared  |          | 664 |            2 | backend     | 330161 |
     |     |         664
 catalog | postgres | 664 |            1 | backend     | 330161 |
     |     |         664
 catalog | db1      | 666 |            1 | backend     | 330353 |
     |     |         666
 data    | postgres | 664 |            1 | backend     | 330161 |
     |     |         664
 data    | db1      | 666 |            1 | backend     | 330353 |
     |     |         666
(5 rows)
```

What I like about something like this is that it is condensed and easy
for a DBA to act on.  They get the global horizon in the "shared" row,
and they also get the per-database xmin horizons.  source_count tells
the DBA when there is more than one potential blocker, but we show the
oldest one that should be acted on first.  So I wonder if this is a
better starting point than exposing one row per source, while keeping
the source-attribution details simpler for the first version?

If someone wants to expand this into all matching sources, they can
write more complex queries on top of the base function.  But for a view
that is meant to provide actionable information to a DBA, I think this
shape is much easier to use.

The VACUUM logging angle [3] also needs to be considered, but not for
this patch.  IMO, getting this view right is more important than VACUUM
logging for now.  But ComputeXidHorizonsData() could in the future be
taught to report for one database only, so we can identify blockers for
the database being vacuumed.


[1] https://wiki.postgresql.org/wiki/User:Andresfreund/Desired_Changes
[2] https://www.postgresql.org/message-id/20231026174136.4et3ktuegmtlgxfs@awork3.anarazel.de
[3] https://www.postgresql.org/message-id/CAOzEurSgy-gDtwFmEbj5+R9PL0_G3qYB6nnzJtNStyuf87VSVg@mail.gmail.com

--
Sami Imseih
Amazon Web Services (AWS)


Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Sami, Scott,

Two things that might help with the shape question.

First, there is committer precedent for both shapes.  Sami found Andres's
2023 sketch [1], with one row per database plus a NULL-datname row for the
system-wide horizons.  In the 2020 "Expose oldest xmin as SQL function for
monitoring" thread, Tom described the other one [2]: "I was envisioning a
view that would show you *all* the active processes and their related
xmins, then more entries for all active replication slots, prepared
xacts, etc etc.  Picking out the ones causing trouble is then the user's
concern."  So both representations have been asked for, which makes me
think the question may be which one is the base and which is built on
top, not which one to have.

Second, on "a query over the patch's rows produces the summary": I think
that's true with two exceptions, and v7 already documents both.  When no
row contributes to a horizon, the horizon advances to a baseline just
past the newest completed xid, "which this view does not display".  And
the combined slot xmins "update only when a slot changes", so "a stale
value that no row shows can briefly pin a horizon".  Those are the values
a per-horizon summary row would need to report the horizon correctly.  If
the function also returned them, as Sami's ComputeXidHorizonsData()
sketch does for the baseline, a per-horizon summary could be built as a
view over the per-source rows, at least on a primary, and both shapes would be available.

[1] https://www.postgresql.org/message-id/20231026174136.4et3ktuegmtlgxfs@awork3.anarazel.de
[2] https://www.postgresql.org/message-id/30712.1585854944@sss.pgh.pa.us

Regards,
Surya Poondla

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
Hi Sami,

On Monday, September 28th, 2026 at 12:36 PM, Sami Imseih  wrote:

> After thinking about this some more, I think the right level for the
> shared part is the small procarray rules next to ComputeXidHorizons(),
> rather than a new procarrayfuncs.c file.

ComputeXidHorizons() and GetXidHorizonProcs() already share what they
can.  The patch adds procarrayfuncs.c for SQL access, following
lockfuncs.c, slotfuncs.c, and xlogfuncs.c.

> returns latestCompletedXid + 1, the recovery KnownAssignedXids xmin, and
> PGPROC entries that can affect horizons, with their classification
> (backend, prepared transaction, or standby feedback), database OID, and
> effective xmin.

Bharath asked for standby support as well [4], and v8 adds it.

> I did not read "sources" here as necessarily meaning one row per PID.  I
> went digging into older conversations and found [2], where Andres lays
> out a potential shape for this view, where we key every row by "datname"
> and "horizon", and where the shared horizon itself is a NULL datname.

Andres sketched a different view in [2] than "all the sources" [1]
suggests.

> So I think we can start out with a function like this which just returns
> the data for each datid/horizon, such as:
> ...
> And using the base function, we can construct a system view, or document
> a way to use it with joins on other system views to come up with a view
> that looks like:

Your base function returns no pid, slot_name or gid, but your derived
view shows all three.  Please see previous discussion in this thread
about limitations of joining existing system views.

> So I wonder if this is a
> better starting point than exposing one row per source, while keeping
> the source-attribution details simpler for the first version?

Your summary achieves simplicity by hiding information that DBAs need,
including the other sources and gaps between their xmins.  The horizon
moves only when all sources stop pinning it to its current value, and
the next pinner determines how much it moves.  A DBA might cancel a
long-running query only to observe the horizon move by one XID and
become pinned by a pg_dump the summary hid.

> What I like about something like this is that it is condensed and easy
> for a DBA to act on.

Cybertec [5], Citus [6], pganalyze [7] and Azure [8] all attempt to
list every source, which suggests DBAs do not need a "condensed"
summary.

[4] https://www.postgresql.org/message-id/CALj2ACWiuAh0BmePj1J7U_KtK1KE8rY89kN5BvWD+qUjmzAsAg@mail.gmail.com
[5] https://www.cybertec-postgresql.com/en/reasons-why-vacuum-wont-remove-dead-rows/
[6] https://www.citusdata.com/blog/2022/07/28/debugging-postgres-autovacuum-problems-13-tips/
[7] https://pganalyze.com/docs/checks/vacuum/xmin_horizon
[8] https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/how-to-autovacuum-tuning

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
Hi Surya,

On Tuesday, September 29th, 2026 at 11:28 AM, surya poondla  wrote:

> So both representations have been asked for, which makes me
> think the question may be which one is the base and which is built on
> top, not which one to have.

Any summary hides information DBAs need, and everyone will have a
different favorite interface, which Sami's proposal and Andres' 2020
and 2023 messages demonstrate.  For pg_stat_progress, Robert thought
it "much better to report slightly more detailed information and let
the user figure out what to do with it" and left any other interface
for later agreement [1].  This patch will take the same approach.

> When no
> row contributes to a horizon, the horizon advances to a baseline just
> past the newest completed xid, "which this view does not display".

pg_snapshot_xmax(pg_current_snapshot()) suffices.

> And
> the combined slot xmins "update only when a slot changes", so "a stale
> value that no row shows can briefly pin a horizon".  Those are the values
> a per-horizon summary row would need to report the horizon correctly.

Like the proc flags, the slot cache represents an implementation detail
that does not belong in any public interface.

[1] https://www.postgresql.org/message-id/CA+TgmoZqXUhTxvX6Z5M76_PFo63DJsKqCFxk-zC+KxpXKDBt=g@mail.gmail.com

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
v9 applies to 9e7d152488f and changes only the TAP test number.

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
v10 applies to master commit 45fc51fcbf4.  It increases the TAP test
number, removes an inaccurate example from the commit message, and
adjusts the documentation to reflect database scoping rules during
recovery.

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Вложения:
Hi,

On Tue, Sep 29, 2026 at 11:28 AM surya poondla  wrote:
>
> Andres's 2023 sketch [1], with one row per database plus a NULL-datname row for the
> system-wide horizons.
> Tom described the other one [2]: *all* the active processes and their related
> xmins, then more entries for all active replication slots, prepared
> xacts, etc etc.  Picking out the ones causing trouble is then the user's
> concern.
>
> [1] https://www.postgresql.org/message-id/20231026174136.4et3ktuegmtlgxfs@awork3.anarazel.de
> [2] https://www.postgresql.org/message-id/30712.1585854944@sss.pgh.pa.us

I have been looking at this. I tend to agree with Tom's thoughts, that
is, core emits all the processes, slots, prepared xacts etc. along
with their xmins, and the summary views could be built by the users.
I'm sure the users will need different flavors of the info such as
what is stopping vacuum per-database and per-cluster, top N blockers,
or, if the oldest blocker goes away, how far the xmin horizon moves,
those only blocking the catalog xmin horizon etc. etc., and they may
even join it with other existing views to get a nice readable format
or such. And, I don't mind optionally having a couple of common
summary SQL views on top of this in core.

I looked at v10 again and it is mostly on the above lines. However, I
think the patch is unnecessarily big at ~1480 LoC (for example, the
tests don't have to be that long, the docs seem to be overly
explaining things, and some code is unnecessarily complicated). And,
the columns it emits seem to be too confusing, there are just too many
xmins (shared, catalog and data horizon).

I think we can simplify it a lot. How about something like the
attached? I could bring it down to ~450 LoC with simplified docs, code
and tests (for the same coverage). For example, the output with this
patch is at [1] vs v10 is at [2], and one can build a summary view
such as [3].

[1]
```
SELECT * FROM pg_xmin_horizon ORDER BY xmin;
       kind        |  pid  | slot_name |  gid   | datid | xmin
-------------------+-------+-----------+--------+-------+------
 slot_catalog_xmin |       | sub_slot  |        |       |  669
 slot_catalog_xmin |       | standby1  |        |       |  677
 backend           | 12122 |           |        | 16384 |  679
 slot_xmin         |       | standby1  |        |       |  681
 standby_feedback  | 12060 |           |        |       |  683
 backend           | 12165 |           |        |     5 |  685
 backend           | 12189 |           |        |     5 |  686
 prepared_xact     |       |           | order1 | 16384 |  686
 backend           | 12174 |           |        | 16384 |  687
(9 rows)
```

[2]
```
SELECT * FROM pg_xmin_horizon ORDER BY age(shared_xmin) DESC NULLS LAST;
       kind       |  pid  | slot_name |  gid   | datid | datname  |
xid | shared_xmin | catalog_xmin | data_xmin |          xact_start
------------------+-------+-----------+--------+-------+----------+-----+-------------+--------------+-----------+-------------------------------
 replication_slot |       | sub_slot  |        | 16384 | db1      |
 |         669 |          669 |           |
 replication_slot |       | standby1  |        |       |          |
 |         677 |          677 |       681 |
 backend          | 11880 |           |        | 16384 | db1      |
 |         679 |          679 |       679 | 2026-11-16
11:35:15.71561-08
 standby_feedback | 11818 |           |        |       |          |
 |         683 |          683 |       683 |
 backend          | 11923 |           |        |     5 | postgres |
 |         685 |          685 |       685 | 2026-11-16
11:35:17.323817-08
 backend          | 11947 |           |        |     5 | postgres |
 |         686 |          686 |       686 | 2026-11-16
11:35:24.383231-08
 prepared_xact    |       |           | order1 | 16384 | db1      |
686 |         686 |          686 |       686 | 2026-11-16
11:35:17.834223-08
 backend          | 11932 |           |        | 16384 | db1      |
687 |         687 |          687 |       687 | 2026-11-16
11:35:17.839764-08
(8 rows)
```

[3]
```
-- Show what is stopping vacuum per-database i.e. the oldest blocker.
SELECT DISTINCT ON (d.datname) d.datname, x.kind, x.pid, x.slot_name,
x.gid, x.xmin
FROM pg_database d
     JOIN pg_xmin_horizon x
       ON x.datid = d.oid OR x.kind NOT IN ('backend',
'prepared_xact', 'slot_catalog_xmin')
ORDER BY d.datname, x.xmin;
  datname  |   kind    |  pid  | slot_name | gid | xmin
-----------+-----------+-------+-----------+-----+------
 db1       | backend   | 12122 |           |     |  679
 postgres  | slot_xmin |       | standby1  |     |  681
 template0 | slot_xmin |       | standby1  |     |  681
 template1 | slot_xmin |       | standby1  |     |  681
(4 rows)
```

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Bharath, Scott,

Bharath's v11 removes the duplicated classifier by recording the inputs
inside ComputeXidHorizonsInternal(), which addresses the concern
Horiguchi, Sami and Bharath raised previously, and an xid8 xmin makes the obvious
ORDER BY work.

One thing I'd like to keep from v10 is the xid column.  In v11 a backend
row's xmin is the older of its xid and xmin, so a backend that owns the
oldest xid and backends that merely took snapshots after it look the
same.  With one idle-in-transaction session and twenty readers whose
xmin equals its xid, that's twenty-one identical rows, and only one of
them is worth terminating.  Scott added xid in v5 for that reason.  The proc's xid is still available at the point where v11 records its inputs,
so keeping it would cost one field in XidHorizonProc and one column.

Regards,
Surya Poondla

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi,

On Tue, Nov 17, 2026 at 1:32 PM surya poondla  wrote:
>
> One thing I'd like to keep from v10 is the xid column.  In v11 a backend
> row's xmin is the older of its xid and xmin, so a backend that owns the
> oldest xid and backends that merely took snapshots after it look the
> same.  With one idle-in-transaction session and twenty readers whose
> xmin equals its xid, that's twenty-one identical rows, and only one of
> them is worth terminating.

I would like the p_x_h view to report what goes into computing the
xmin horizon (in this case, the older of the txn's xmin and xid). And,
users need to look at one of the existing views depending on the
blocker type (p_s_a, p_r_s, p_s_r_s, or p_p_x) to find out what
exactly the blocker is doing, and then decide. I don't think we can
avoid that, otherwise we would end up duplicating many of the columns
from existing views in the p_x_h view, which I don't think is a great
idea.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com


Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
Hi Bharath,

Thanks for posting v11.  I noticed it names me as its only author.  If
you intended to give me credit, thank you, but please do not post code
you wrote under my name.

On Monday, November 16th, 2026 at 1:41 PM, Bharath Rupireddy  wrote:

> However, I
> think the patch is unnecessarily big at ~1480 LoC (for example, the
> tests don't have to be that long, the docs seem to be overly
> explaining things, and some code is unnecessarily complicated).

Relative to v10, v11 removes 1034 lines, 627 of them tests.

> I could bring it down to ~450 LoC with simplified docs, code
> and tests (for the same coverage).

The coverage is not the same.  v11's tests never read any xmin, never
produce a slot_xmin row, and never check that access requires
pg_read_all_stats.  I changed v11 to return 42 for every xmin and emit
no slot_xmin rows, and no test failed.

v11 reduces length further by deleting additions requested by reviewers.
v2 added datname at Solai's suggestion [1].  v5 added xid and a test
for a slot whose effective_xmin is set while data.xmin is still
invalid, and v6 made the SRF read fresh transaction start times, all
at Surya's request [2][3].  v11 drops these, and your mail gives no
reason other than the patch's size.  Size alone would justify removing
anything.  If you think these are not worth having, please say why
for each, so the reviewers who asked for them can respond.

The simplified docs omit material I added after you asked in [4]: the
notes on parallel workers and the SQL decoding functions (items 27 and
28) and the ANALYZE exception (item 29).  They also lack information I
added unprompted because users need it: rows can tie, and a standby
shows the primary's transactions as of the standby's replay position.

v11 also returns gid from pg_get_xmin_horizon().  In item 7 of [4],
you wrote:

> The join also means gid reads null if the prepared transaction
> ends in between, for a row the view still reports.

In [5], I asked which locks the function would hold while it reads the
gid.  v11 releases ProcArrayLock, then calls TwoPhaseGetGid(), which
takes only TwoPhaseStateLock.  If the prepared transaction ends between
the proc array scan and that call, v11 still emits the row with a null
gid.  Moving the lookup into C adds code without closing that window.

v11 also uses a row-building helper of the kind I declined in my reply
to item 25 of [4].  Calls to xmin_horizon_put_row() pass eight
arguments by position and are hard to read.  v10 zeroes each row and
assigns fields by name.  Like pg_stat_get_activity(),
pg_stat_get_wal_senders(), pg_prepared_xact(), and
pg_get_replication_slots(), it emits rows in one place.  v11 emits
through its helper from six places.  With v10's columns, such a helper
would save about 30 lines, but each call would pass ten arguments by
position.  Five adjacent ones would be uint32, so the compiler could
not catch two of them swapped.

> And,
> the columns it emits seem to be too confusing, there are just too many
> xmins (shared, catalog and data horizon).

I can read this two ways.  One is that three xmin columns are too many
to look at.  Users can solve that by selecting the ones they want.
The other is that it's too confusing that there is more than one
horizon and that a row can hold back different horizons at different
values.  v11 does not remove that confusion.  It shifts most of that
complexity into the documentation, making horizon scoping easier to
overlook and requiring the user to apply more rules by hand.

Take the last query in your email.  Writing it required choosing a
horizon and identifying which rows hold the horizon back.  A user who
thinks there is only one horizon will not know that the query may
exclude logical slots that bloat the catalogs or that removing the
oldest row in the view might do nothing for a user table.

v11 splits a slot with both an xmin and a catalog_xmin into two rows.
Why is one slot row with a column per horizon more confusing than two
rows?

On a standby, v11 emits one primary_xact row for every transaction ID
in KnownAssignedXids, subtransactions included.  A transaction with
two savepoints can yield three rows, and the view does not indicate
such rows are related.  The documentation says to query the view on
the primary to find the transaction, but a subtransaction's ID does
not appear there.

I will reply to Surya, attach v12 there, and address logic duplication
and the xid column.

[1] https://postgr.es/m/CAF0whuesEDciXVLLPpSs72OMgzXzbbO9xTd-vDVcfhi0ZrDNNg@mail.gmail.com
[2] https://postgr.es/m/CAOVWO5p8boS_gcjVTJs8A=VkC_uz1OL0KjeZh6SBeUqsfbHzzg@mail.gmail.com
[3] https://postgr.es/m/CAOVWO5pTmggE5Z5cx12N_am4=4r76CwpgR9X591HcM5Q6FLNFw@mail.gmail.com
[4] https://postgr.es/m/CALj2ACXg+UQhtwZ5oiuvrx+1XKk49N6cu=wP5Cmv627_=zjsOg@mail.gmail.com
[5] https://postgr.es/m/qhODUcdKmqtOtwF4bW03SxPfKHda4EC7CEO2Ddj2jThrGRa8F1pDMA7LtG0R5JRo-2GK5RStXVP7tPP7WAUvfb_GCSN_I_YG7khDW859Fxg=@scottray.io

--
Scott Ray

Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon

От:
Scott Ray <scott@scottray.io>
Дата:
Вложения:
Hi Surya,

On Tuesday, November 17th, 2026 at 1:32 PM, surya poondla  wrote:

> Bharath's v11 removes the duplicated classifier by recording the
> inputs inside ComputeXidHorizonsInternal(), which addresses the
> concern Horiguchi, Sami and Bharath raised previously,

Sami described that design in [1] and set it aside:

> Initially, I thought about a ComputeXidHorizonsInternal() which takes a
> bool called with_horizon_data and returns the data needed by the SQL
> function.  ComputeXidHorizons() would then become a wrapper for
> ComputeXidHorizonsInternal() with with_horizon_data = false.  I did not
> have any performance concerns with this approach, but I also no longer
> like the idea of turning ComputeXidHorizons() into a multi-purpose
> function.

I agree.

Horiguchi raised his concern about GetXidHorizonBlockers() in the
other thread [2].  He asked for a helper that both functions could
use.  Kato added ProcAffectsDataHorizon() and kept the two callers
separate [3].  In May, I asked whether the blocker could be found
inside ComputeXidHorizons(), and Kato preferred to keep the two
responsibilities separate [4].  When Bharath proposed it, Kato
declined again [5].

v10 keeps a separate function as well, but it contains a bug that v12
fixes: during recovery, a backend with no database holds back every
horizon, but v10 shows only shared_xmin.  In my first mail [6], I said
I expect Kato's patch to be committed first.  The SRF could
call ProcAffectsDataHorizon() and maybe other shared helpers.  In my
reply to Sami [7], I said that ComputeXidHorizons() and
GetXidHorizonProcs() "already share what they can".  That overstated
it, and the bug above is in a rule they do not share.  Kato's patch
moves that rule into ProcAffectsDataHorizon().  I plan to build on his
helper rather than add competing helpers now.

v11 shares only two rules through ComputeXidHorizonsInternal(): which
processes are exempt, and taking the older of xid and xmin.  v12
shares the first through a macro and restates the second in one line.
The rule v10 got wrong is not one of the two.  v11 does not apply it
and describes it in the documentation instead.

For slots, v11 records nothing inside ComputeXidHorizonsInternal().
Like v12, it reads them again in its own loop.  v12's loop restates
the rule that a slot's catalog_xmin holds back the shared and catalog
horizons but not the data horizon.  v11's does not, because it does
not apply the rule.  It leaves that to users.

> and an xid8 xmin makes the obvious ORDER BY work.

Yes, but no system view and no catalog uses an xid8 column.  Using
xid8 with values from pg_stat_activity, pg_prepared_xacts,
pg_replication_slots, or pg_locks requires casting, and age() does not
accept xid8.  I would rather the new view match the others.

> One thing I'd like to keep from v10 is the xid column.

v12 keeps it.  Bharath replied that the view should report what goes
into computing the horizon and leave the rest to the existing views.
A backend's xid goes into that computation.  As you say, without it a
backend that holds the horizon back with its own transaction looks
the same as one that holds it back with a snapshot.  And v11 does not
leave the rest to the existing views.  For example, it adds a C
function to return the gid, which is already in pg_prepared_xacts.

v12 is attached and applies to master commit 736ecc413b3.  Besides the
recovery fix above, it corrects several statements in the
documentation and comments, fixes two races and an ineffective check
in the tests, and renumbers the TAP test.

[1] https://postgr.es/m/CAN12+YLOLcsePG8r9m9gTomXHbJ6ynd+-eLHmoN4eoBBQMSVKw@mail.gmail.com
[2] https://postgr.es/m/20260629.172207.542761264338459554.horikyota.ntt@gmail.com
[3] https://postgr.es/m/CAOzEurQSYUD64pGnbwgxHb_xUhHsO486Y1ZdV=dJugu922q+hA@mail.gmail.com
[4] https://postgr.es/m/CAOzEurTC+5xuH_X2EBWjW0Fs9iuTq3OMA=1FfT4xx1wYbCAR6g@mail.gmail.com
[5] https://postgr.es/m/CAOzEurTr-Z43BPSAz1cW=SiFsMk_AjC4qLAKfG2c09skL9Zn8w@mail.gmail.com
[6] https://postgr.es/m/AT-erSWn0vFw8TYLb84jqyfxgTV21gjwEo4YJDcses8qWtDkQK_pS6g2OIfVh4-L1PPn94w8-tE1mHZactVAgxPJ8vL96MXsyAnUg2Xz-Ks=@scottray.io
[7] https://postgr.es/m/i2q1k7cXS05oPhU_tBZfXKJ0tgqQ6unlVDrB8EhjjazAHmGhX3Qk9AAhybbf59b0yA_BH66GWzTc1hwvnnJb5WFApD1apw6DTrhAZSHqL3E=@scottray.io

--
Scott Ray
FAQ