On 11/9/26 09:49, Ayush Tiwari wrote:
>
> ...
>>
>> 2) statement timeout reported as "user request" cancellation
>>
>> While looking at the code and trying to come up with reproducers for the
>> first issue, I ran into a second race, where we correctly cancel the
>> query due to a timeout, but report it happened due to a "user request".
>>
>> It can happen if the timeout expires while parsing a long query string
>> (yes, that's not very common), because that does not check interrupts.
>> In exec_simple_query() we start the timer, do parsing etc., and then
>> call enable_statement_timeout() again, which does this:
>>
>>     if (!get_timeout_active(STATEMENT_TIMEOUT) &&
>>         !get_timeout_indicator(STATEMENT_TIMEOUT, false))
>>         enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
>>
>> But get_timeout_active(() returns false if the timer already fired, so
>> the timer gets restarted, but leaves QueryCancelPending set. And so on
>> the next CHECK_FOR_INTERRUPTS() the query gets cancelled with the
>> misleading "canceling statement due to user request" reason.
>>
>> I'm attaching a SQL reproducer for this too (repro-parse.sql), hitting
>> this. It's a bit artificial, I don't think I've seen this in practice
>> (even though some of the queries the stress test produces are long and
>> complex). 0002 fixes that by not restarting the timer that has fired
>> (which relies on the previous commit).
> 
> I was poking at this a bit, and I think it would be good to also check
> QueryCancelPending there, i.e. only skip the restart while the cancel
> is actually still pending:
> 
>     if (!get_timeout_active(STATEMENT_TIMEOUT) &&
>         !(QueryCancelPending &&
>           get_timeout_indicator(STATEMENT_TIMEOUT, false)))
>         enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
> 
> Otherwise, if the cancel already got handled somewhere else (e.g. in the
> sync rep wait), the indicator stays set and the next query can end up
> running without any statement timeout.
> 
> It's a pretty narrow case, but seems worth fixing.
> 

Yeah, thanks for noticing that. I agree this this can happen, and it
would prevent starting the statement timeout after that. But I'm not
sure this is the right fix, as it seems to contradict the comment before
enable_statement_timeout (and the contract for these functions).

The 0001 commit should probably spell out the behavior/contract change
more explicitly. Before the commit, enable_statement_timeout() would
start the timeout unless it's already active. With 0001 the timeout is
started only if it's neither active nor fired. I think adding the
QueryCancelPending check would make this less clear.

I was wondering if syncrep is the only place with this issue, and it
seem it is. The other places clearing QueryCancelPending seems safe:

* Autovacuum workers force statement_timeout and lock_timeout to 0, so
those timeouts are never started in that context.

* Error recovery in PostgresMain() and in the autovacuum launcher calls
disable_all_timeouts(false) first, which resets them.

* ProcessInterrupts() and disable_statement_timeout() reset both timeout
indicators themselves.

* ProcessInterrupts() and proc_exit_prepare() clear the flag right
before the process exits, so who cares if the timeouts run.

The non-exit cases are safe because they reset/disable the timeouts,
making the stale indicator impossible. Syncrep is the only case not
doing that. I think that's the root cause, and it'd be better to fix
that by doing roughly:

    if (QueryCancelPending)
    {
        QueryCancelPending = false;
        (void) get_timeout_indicator(LOCK_TIMEOUT, true);
        (void) get_timeout_indicator(STATEMENT_TIMEOUT, true);
        ereport(WARNING, ...);
    }

Attached is v2 doing it this way.

BTW the earlier patches suggested I'm planning to backpatch this (to all
supported branches), but I've changed my mind and probably won't do
that. At least not initially. I've not seen a single report about these
issues, it's not worth the risk.


regards

-- 
Tomas Vondra
From dec91d1e6402bb827696506e2ac30b04645450ed Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Mon, 9 Nov 2026 00:30:25 +0100
Subject: [PATCH v2 2/2] Don't restart a statement timeout that has already
 fired.

Since commit 22f6f2c1ccb, enable_statement_timeout() relies on
get_timeout_active() to avoid restarting a running timeout, but that
returns false once the timeout has fired. If the timeout fires while
exec_simple_query() parses a long query string, which doesn't check for
interrupts, the next start_xact_command() restarts it, resetting its
indicator, so the pending cancel request is reported as "canceling
statement due to user request" instead of a statement timeout.

To fix, don't restart the timer while the indicator is set.  This relies
on the previous commit resetting the indicator at the end of each
statement; otherwise a stale indicator could keep later statements from
being timed out.

The only relevant place resetting QueryCancelPending without also
resetting the indicator was SyncRepWaitForLSN().  When that happened,
later commands would not have a statement timeout active.  Fix by
resetting both indicators (for statement and lock timeouts) in
SyncRepWaitForLSN() too.

Author: Tomas Vondra <[email protected]>
Reviewed-by: Chao Li <[email protected]>
Reviewed-by: Ayush Tiwari <[email protected]>
Reviewed-by: surya poondla <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/replication/syncrep.c | 11 +++++++++++
 src/backend/tcop/postgres.c       | 21 +++++++++++++--------
 2 files changed, 24 insertions(+), 8 deletions(-)

diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index d870f09e0a0..1216baf0de2 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -85,6 +85,7 @@
 #include "tcop/tcopprot.h"
 #include "utils/guc_hooks.h"
 #include "utils/ps_status.h"
+#include "utils/timeout.h"
 #include "utils/wait_event.h"
 
 /* User-settable parameters for sync rep */
@@ -323,10 +324,20 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 		 * can't actually abort at this point, but ignoring the interrupt
 		 * altogether is not helpful, so we just terminate the wait with a
 		 * suitable warning.
+		 *
+		 * The request may have come from the statement or lock timeout, so
+		 * reset their indicators, as ProcessInterrupts() does.  We do this
+		 * for two reasons.  First, enable_statement_timeout() doesn't start
+		 * the timer while the statement timeout's indicator is set, so the
+		 * next statement would run without a statement timeout. Second, a
+		 * query cancel arriving while waiting for the next message would be
+		 * reported as a timeout, rather than ignored.
 		 */
 		if (QueryCancelPending)
 		{
 			QueryCancelPending = false;
+			(void) get_timeout_indicator(LOCK_TIMEOUT, true);
+			(void) get_timeout_indicator(STATEMENT_TIMEOUT, true);
 			ereport(WARNING,
 					(errmsg("canceling wait for synchronous replication due to user request"),
 					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index a1c63bcd504..bb362dbb81c 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -5375,7 +5375,10 @@ log_disconnections(int code, Datum arg)
  *
  * If there's already a timeout running, don't restart the timer.  That
  * enables compromises between accuracy of timeouts and cost of starting a
- * timeout.
+ * timeout.  Likewise, don't restart it if it has already fired, but the query
+ * cancel request it sent hasn't been serviced yet (e.g. because it fired
+ * while parsing a long query string).  Restarting it would reset its
+ * indicator, causing the request to be reported as a user request.
  */
 static void
 enable_statement_timeout(void)
@@ -5386,7 +5389,8 @@ enable_statement_timeout(void)
 	if (StatementTimeout > 0
 		&& (StatementTimeout < TransactionTimeout || TransactionTimeout == 0))
 	{
-		if (!get_timeout_active(STATEMENT_TIMEOUT))
+		if (!get_timeout_active(STATEMENT_TIMEOUT) &&
+			!get_timeout_indicator(STATEMENT_TIMEOUT, false))
 			enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
 	}
 	else
@@ -5399,12 +5403,13 @@ enable_statement_timeout(void)
 /*
  * Disable statement timeout, if active.
  *
- * If the statement timeout has already fired, but the statement completed
- * without reaching a CHECK_FOR_INTERRUPTS() afterwards, the query cancel
- * request sent by the timeout is still pending.  Discard it, as otherwise
- * it would cancel whatever we do next.  This also discards a cancel request
- * from the user that arrived at about the same time, since we can't tell
- * them apart, but that seems acceptable: the statement has completed anyway.
+ * This is called whenever a statement completes.  If the statement timeout
+ * has already fired, but the statement completed without reaching a
+ * CHECK_FOR_INTERRUPTS() afterwards, the query cancel request sent by the
+ * timeout is still pending.  Discard it, as otherwise it would cancel
+ * whatever we do next.  This also discards a cancel request from the user
+ * that arrived at about the same time, since we can't tell them apart, but
+ * that seems acceptable: the statement has completed anyway.
  */
 static void
 disable_statement_timeout(void)
-- 
2.56.0

From 2208e9c68fe0d7f50d8401dc00e68ef8e9045b22 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Mon, 9 Nov 2026 00:26:55 +0100
Subject: [PATCH v2 1/2] Discard pending timeout cancel requests at end of
 statement.

If statement_timeout fires and the statement then completes without
reaching a CHECK_FOR_INTERRUPTS(), the timeout's cancel request is left
pending.  Before commit 22f6f2c1ccb (v13), disable_statement_timeout()
reset the timeout's indicator, so the request was ignored while reading
the next command.  Since then, it does nothing once the timeout has
fired, so the next command fails with a statement timeout without being
executed.

This is relatively easy to hit without special privileges, e.g. with
CALL or FETCH, which don't check for interrupts after evaluating a
long-running expression.  Of course, most systems either don't have the
statement_timeout set at all, or there's a significant margin.

To fix, make disable_statement_timeout() always fetch and reset the
indicator, and discard the pending request if it was set.  Likewise for
lock_timeout, which can leave a request behind if it fires just as the
lock is granted.  ProcessInterrupts() uses this pattern too.  This also
discards a user's cancel request arriving at about the same time, which
seems acceptable, as the statement has completed anyway.

Author: Tomas Vondra <[email protected]>
Reviewed-by: FIXME
Discussion: FIXME
Backpatch-through: 15
---
 src/backend/tcop/postgres.c | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index d6761aeea9f..a1c63bcd504 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -5398,10 +5398,32 @@ enable_statement_timeout(void)
 
 /*
  * Disable statement timeout, if active.
+ *
+ * If the statement timeout has already fired, but the statement completed
+ * without reaching a CHECK_FOR_INTERRUPTS() afterwards, the query cancel
+ * request sent by the timeout is still pending.  Discard it, as otherwise
+ * it would cancel whatever we do next.  This also discards a cancel request
+ * from the user that arrived at about the same time, since we can't tell
+ * them apart, but that seems acceptable: the statement has completed anyway.
  */
 static void
 disable_statement_timeout(void)
 {
+	bool		lock_timeout_occurred;
+	bool		stmt_timeout_occurred;
+
+	/* Keep the indicator in case the timeout fires right now; see below */
 	if (get_timeout_active(STATEMENT_TIMEOUT))
-		disable_timeout(STATEMENT_TIMEOUT, false);
+		disable_timeout(STATEMENT_TIMEOUT, true);
+
+	/*
+	 * A lock timeout that fired just as the lock was granted can leave a
+	 * pending cancel request behind in the same way (see ProcSleep()). Always
+	 * fetch and reset both indicators, as in ProcessInterrupts().
+	 */
+	lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
+	stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
+
+	if (lock_timeout_occurred || stmt_timeout_occurred)
+		QueryCancelPending = false;
 }
-- 
2.56.0

Reply via email to