From d32400881e181f360e064b5f0ed0119c3006002e Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Fri, 8 Aug 2025 15:58:05 +0000
Subject: [PATCH v4 2/3] Adding XID generation count per backend

This commit adds a new counter to record the number of XIDs generated per
backend. It will help to detect if a backend is consuming XIDs at a high rate.

Virtual transactions are not taken into account on purpose, we do want to track
only the XID where there is a risk of wraparound.
---
 src/backend/access/transam/varsup.c         | 4 ++++
 src/backend/utils/activity/pgstat_backend.c | 2 ++
 src/include/pgstat.h                        | 2 ++
 3 files changed, 8 insertions(+)
  43.8% src/backend/access/transam/
  36.6% src/backend/utils/activity/
  19.4% src/include/

diff --git a/src/backend/access/transam/varsup.c b/src/backend/access/transam/varsup.c
index f8c4dada7c9..72c8aa7650b 100644
--- a/src/backend/access/transam/varsup.c
+++ b/src/backend/access/transam/varsup.c
@@ -24,6 +24,7 @@
 #include "storage/pmsignal.h"
 #include "storage/proc.h"
 #include "utils/lsyscache.h"
+#include "utils/pgstat_internal.h"
 #include "utils/syscache.h"
 
 
@@ -257,6 +258,9 @@ GetNewTransactionId(bool isSubXact)
 		/* LWLockRelease acts as barrier */
 		MyProc->xid = xid;
 		ProcGlobal->xids[MyProc->pgxactoff] = xid;
+		PendingBackendStats.pending_xid_count++;
+		backend_has_xactstats = true;
+		pgstat_report_fixed = true;
 	}
 	else
 	{
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index 47ce61e5093..5e509153656 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -285,9 +285,11 @@ pgstat_flush_backend_entry_xact(PgStat_EntryRef *entry_ref)
 
 	shbackendent->stats.xact_commit += PendingBackendStats.pending_xact_commit;
 	shbackendent->stats.xact_rollback += PendingBackendStats.pending_xact_rollback;
+	shbackendent->stats.xid_count += PendingBackendStats.pending_xid_count;
 
 	PendingBackendStats.pending_xact_commit = 0;
 	PendingBackendStats.pending_xact_rollback = 0;
+	PendingBackendStats.pending_xid_count = 0;
 
 	backend_has_xactstats = false;
 }
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 0fdbaf79780..d78633cae44 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -492,6 +492,7 @@ typedef struct PgStat_Backend
 	PgStat_WalCounters wal_counters;
 	PgStat_Counter xact_commit;
 	PgStat_Counter xact_rollback;
+	PgStat_Counter xid_count;
 } PgStat_Backend;
 
 /* ---------
@@ -510,6 +511,7 @@ typedef struct PgStat_BackendPending
 	 */
 	PgStat_Counter pending_xact_commit;
 	PgStat_Counter pending_xact_rollback;
+	PgStat_Counter pending_xid_count;
 } PgStat_BackendPending;
 
 /*
-- 
2.34.1

