From 41d9ad49e71da90ce905f1be66f69c54c082111d Mon Sep 17 00:00:00 2001
From: Jingtang Zhang <mrdrivingduck@gmail.com>
Date: Tue, 17 Nov 2026 17:25:29 +0800
Subject: [PATCH v4 2/2] Avoid blocking on client output when reporting FATAL
 errors

A backend that has decided to exit can still block while sending the
fatal error to a client that is not reading. Try to send the error
without waiting, then suppress further client output during exit
cleanup.

Preserve the existing suppression of messages generated during a write
by skipping the nested enqueue before it can resize the send buffer.

Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com>
---
 src/backend/libpq/pqcomm.c                   |  4 ++
 src/backend/utils/error/elog.c               | 18 +++++++++
 src/test/modules/test_misc/t/005_timeouts.pl | 39 ++++++++++++++++++++
 3 files changed, 61 insertions(+)

diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
index 3704d121003..0460de665ce 100644
--- a/src/backend/libpq/pqcomm.c
+++ b/src/backend/libpq/pqcomm.c
@@ -1524,6 +1524,10 @@ socket_putmessage_noblock(char msgtype, const char *s, size_t len)
 	int			res PG_USED_FOR_ASSERTS_ONLY;
 	int			required;
 
+	/* Avoid resizing the send buffer for a message we'd drop anyway. */
+	if (PqCommBusy)
+		return;
+
 	/*
 	 * Ensure we have enough space in the output buffer for the message header
 	 * as well as the message itself.
diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index e215ed053ff..e7f8a6fa242 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -4128,6 +4128,24 @@ send_message_to_frontend(ErrorData *edata)
 
 		pq_sendbyte(&msgbuf, '\0'); /* terminator */
 
+		/*
+		 * On a client socket, don't let a FATAL report delay process exit.
+		 * Suppress further client output after the send attempt.  Workers that
+		 * report errors through a shared-memory queue use the regular path.
+		 */
+		if (edata->elevel == FATAL && MyProcPort != NULL)
+		{
+			pq_putmessage_noblock(msgbuf.cursor, msgbuf.data, msgbuf.len);
+			pfree(msgbuf.data);
+
+			(void) pq_flush_if_writable();
+
+			if (whereToSendOutput == DestRemote)
+				whereToSendOutput = DestNone;
+
+			return;
+		}
+
 		pq_endmessage(&msgbuf);
 	}
 	else
diff --git a/src/test/modules/test_misc/t/005_timeouts.pl b/src/test/modules/test_misc/t/005_timeouts.pl
index 79ff980f1d6..64f21e0152c 100644
--- a/src/test/modules/test_misc/t/005_timeouts.pl
+++ b/src/test/modules/test_misc/t/005_timeouts.pl
@@ -203,4 +203,43 @@ ok( $node->poll_query_until(
 	'transaction timeout terminates the backend during ClientRead');
 $psql_session->{run}->finish;
 
+#
+# 6. Test that sending a FATAL error cannot block backend exit.
+#
+$psql_session = $node->background_psql('postgres');
+$pid = $psql_session->query_safe('SELECT pg_backend_pid()');
+$log_offset = -s $node->logfile;
+
+# Send a query in pipeline mode and leave its results unread. The dynamic
+# query text makes the FATAL error context larger than the socket buffers.
+# Turn off ON_ERROR_STOP for \flush, since psql treats PQflush's successful
+# return of zero as a failure.
+$psql_session->query_until(
+	qr/sleep_sent/, q[
+   BEGIN;
+   SET LOCAL log_error_verbosity = 'terse';
+   SET LOCAL max_parallel_workers_per_gather = 0;
+   SET LOCAL transaction_timeout = '5s';
+   \startpipeline
+   DO $$
+   BEGIN
+     EXECUTE 'SELECT pg_sleep(60) /*' || repeat('x', 8 * 1024 * 1024) || '*/';
+   END;
+   $$;
+   \set ON_ERROR_STOP off
+   \flush
+   \echo sleep_sent
+]);
+$node->wait_for_event('client backend', 'PgSleep');
+
+$node->wait_for_log(
+	qr/\[$pid\].*FATAL:\s+terminating connection due to transaction timeout/,
+	$log_offset);
+ok( $node->poll_query_until(
+		'postgres', qq[
+		SELECT NOT EXISTS (SELECT FROM pg_stat_activity WHERE pid = $pid);
+	]),
+	'backend exits even when the client does not read the FATAL error');
+$psql_session->{run}->kill_kill;
+
 done_testing();
-- 
2.43.7

