From 98e5be05ea3d6593856c7ac5b209e1b2c8bf175a Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Thu, 26 Nov 2026 16:12:01 +0200
Subject: [PATCH v2 1/1] Don't report idle stats while starting a transaction

ProcessInterrupts() reports pending stats when the idle stats update
timeout has fired and the backend is idle, waiting for a command.  It
used !IsTransactionOrTransactionBlock() to check that we're not in a
transaction, but that looks only at the transaction block state.  When
an idle backend receives a sinval catchup or notify interrupt,
ProcessClientReadInterrupt() starts a transaction to process it, and
the block state is still TBLOCK_DEFAULT while StartTransaction() runs.
If the timeout fired and CHECK_FOR_INTERRUPTS() was called during
StartTransaction(), for example while processing invalidation messages
in AtStart_Cache(), pgstat_report_stat() was called in TRANS_START
state, and the assertion in GetCurrentTransactionStopTimestamp()
failed.

To fix, add a new function IsCompletelyOutOfTransaction(), which also
checks the low-level transaction state, and use it in
ProcessInterrupts().  Also use it in the sanity check assertion in
pgstat_report_stat(), so that we catch such bugs earlier.

When the stats report is skipped because we're in the middle of
processing a catchup or notify interrupt, ProcessInterrupts() has
already cleared InterruptPending, so the deferred report would not
happen until something else woke up the backend.  To fix that, re-arm
InterruptPending and check for interrupts again in
ProcessClientReadInterrupt() after processing those interrupts.
That's an independent issue, but this fix makes the window for it to
happen wider, so fix that too.

Without assertions, the consequence is only that stats are reported in
the middle of starting a transaction, which is harmless, so no
backpatching.

Reviewed-by: Shihao Zhong <zhong950419@gmail.com>
Reviewed-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Discussion: https://postgr.es/m/42b2c4f9-511e-4b5c-8edd-b474019ddf29@iki.fi
---
 src/backend/access/transam/xact.c   | 31 +++++++++++++++++++++++++++--
 src/backend/tcop/postgres.c         | 22 ++++++++++++++++++--
 src/backend/utils/activity/pgstat.c |  2 +-
 src/include/access/xact.h           |  1 +
 4 files changed, 51 insertions(+), 5 deletions(-)

diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index d8d91bed427..53b59272020 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -5079,8 +5079,11 @@ IsTransactionBlock(void)
 
 /*
  * IsTransactionOrTransactionBlock --- are we within either a transaction
- * or a transaction block?	(The backend is only really "idle" when this
- * returns false.)
+ * or a transaction block?
+ *
+ * This looks only at the transaction block state, so it returns false while
+ * we're in the middle of starting a transaction, before the transaction
+ * block state has been updated.  See also IsCompletelyOutOfTransaction().
  *
  * This should match up with IsTransactionBlock and IsTransactionState.
  */
@@ -5095,6 +5098,30 @@ IsTransactionOrTransactionBlock(void)
 	return true;
 }
 
+/*
+ * IsCompletelyOutOfTransaction --- are we completely out of a transaction?
+ *
+ * The backend is only really "idle" when this returns true.  Note that the
+ * purpose of this function is different from that of IsTransactionState().
+ * IsTransactionState() is used to check if we're in a live transaction where
+ * it's safe to access the database, while IsCompletelyOutOfTransaction() is
+ * used to check if we're completely out of a transaction.  When we're in the
+ * middle of starting or ending a transaction, we're neither in a live
+ * transaction nor completely out of a transaction.
+ *
+ * This differs from !IsTransactionOrTransactionBlock() in that it also checks
+ * the low-level transaction state, so that it returns false while we're in
+ * the middle of StartTransaction(), or cleaning up a transaction that failed
+ * to start.
+ */
+bool
+IsCompletelyOutOfTransaction(void)
+{
+	TransactionState s = CurrentTransactionState;
+
+	return s->blockState == TBLOCK_DEFAULT && s->state == TRANS_DEFAULT;
+}
+
 /*
  * TransactionBlockStatusCode - return status code to send in ReadyForQuery
  */
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index d6761aeea9f..1361dfa5526 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -528,6 +528,19 @@ ProcessClientReadInterrupt(bool blocked)
 		/* Process notify interrupts, if any */
 		if (notifyInterruptPending)
 			ProcessNotifyInterrupt(true);
+
+		/*
+		 * Processing a catchup or notify interrupt can run a transaction.  If
+		 * the idle stats update timeout fired while we were in it,
+		 * ProcessInterrupts() did not report the stats because we were not
+		 * fully idle, but it did clear InterruptPending.  Process the timeout
+		 * now if that happened.
+		 */
+		if (IdleStatsUpdateTimeoutPending)
+		{
+			InterruptPending = true;
+			CHECK_FOR_INTERRUPTS();
+		}
 	}
 	else if (ProcDiePending)
 	{
@@ -3685,10 +3698,15 @@ ProcessInterrupts(void)
 
 	/*
 	 * If there are pending stats updates and we currently are truly idle
-	 * (matching the conditions in PostgresMain(), report stats now.
+	 * (matching the conditions in PostgresMain()), report stats now.
+	 *
+	 * Note that a backend that's waiting for a command can briefly start a
+	 * transaction to process a sinval catchup or notify interrupt, see
+	 * ProcessClientReadInterrupt().  We must not report stats in the middle
+	 * of that, not even while the transaction is being started.
 	 */
 	if (IdleStatsUpdateTimeoutPending &&
-		DoingCommandRead && !IsTransactionOrTransactionBlock())
+		DoingCommandRead && IsCompletelyOutOfTransaction())
 	{
 		IdleStatsUpdateTimeoutPending = false;
 		pgstat_report_stat(true);
diff --git a/src/backend/utils/activity/pgstat.c b/src/backend/utils/activity/pgstat.c
index d31c0b48a1d..5609e6ec072 100644
--- a/src/backend/utils/activity/pgstat.c
+++ b/src/backend/utils/activity/pgstat.c
@@ -744,7 +744,7 @@ pgstat_report_stat(bool force)
 	bool		nowait;
 
 	pgstat_assert_is_up();
-	Assert(!IsTransactionOrTransactionBlock());
+	Assert(IsCompletelyOutOfTransaction());
 
 	/* "absorb" the forced flush even if there's nothing to flush */
 	if (pgStatForceNextFlush)
diff --git a/src/include/access/xact.h b/src/include/access/xact.h
index a8cbdf247c8..f5074b9c84c 100644
--- a/src/include/access/xact.h
+++ b/src/include/access/xact.h
@@ -486,6 +486,7 @@ extern void StartParallelWorkerTransaction(char *tstatespace);
 extern void EndParallelWorkerTransaction(void);
 extern bool IsTransactionBlock(void);
 extern bool IsTransactionOrTransactionBlock(void);
+extern bool IsCompletelyOutOfTransaction(void);
 extern char TransactionBlockStatusCode(void);
 extern void AbortOutOfAnyTransaction(void);
 extern void PreventInTransactionBlock(bool isTopLevel, const char *stmtType);
-- 
2.47.3

