Pushed 0001 patch, thanks for the reviews!

On 24/11/2026 04:13, shihao zhong wrote:
 > Maybe we
 > could leave IsTransactionOrTransactionBlock() as-is and handle this
 > only for the idle stats check?

Give it a try with your idea, it doesn't look that complex, maybe we should fix it?

Makes sense. Attached is another version along those lines. It adds a new function, IsCompletelyOutOfTransaction(), which checks both the block state and the low-level state. So instead of "!IsTransactionOrTransactionBlock() && IsTransactionStateDefault()", you can do just "IsCompletelyOutOfTransaction()". That's easier to read at the call site, and the new function is a natural place for the comment on what "completely out of a transaction" means.

AI review found one little issue. In theory, it's a pre-existing issue, but this patch makes the window for it larger:

ProcessInterrupts() clears InterruptPending when it's called, so once it has skipped the idle stats report in the middle of the catchup transaction, nothing processes IdleStatsUpdateTimeoutPending again until the backend is woken up for some other reason. That defeats the purpose of the idle stats timeout.

To fix that, ProcessClientReadInterrupt() now re-arms InterruptPending if IdleStatsUpdateTimeoutPending is still set after processing the catchup and notify interrupts, and checks for interrupts again. That feels a little ad hoc to me to be honest, but it seems like the best way to fix it without a bigger overhaul. And I'm working on a bigger overhaul, in the "interrupts vs signals" thread, anyway.

What do you think of the attached?

- Heikki
From 98e5be05ea3d6593856c7ac5b209e1b2c8bf175a Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <[email protected]>
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 <[email protected]>
Reviewed-by: Ayush Tiwari <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 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

Reply via email to