From bf0e1069cb6898f24a5607bdf1d0291f1f351be1 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Fri, 13 Dec 2024 01:11:01 +1300
Subject: [PATCH v2 2/2] Adjust pending_pm_pmsignal processing priority.

Commit 239b175 gave high priority to shutdown requests, child exit
notifications, reload requests and PM signals received from backends.

Undo that last case.  While the others have good reasons for
queue-jumping (supremacy of administrative commands, ordering
requirement of reload-connect sequences, and desire to release child
process resources ASAP), PM signals do not.  Let's go back to processing
PM signals only when a WL_LATCH_SET event is received, and thus only
once per server loop.

It didn't make much difference before, because we'd very likely run the
inner loop that scan events[] just once, because only WL_LATCH_SET was
reported in the common case.  Now that we've adjusted WaitEventSetWait()
to return WL_LATCH_SET and potentially WL_SOCKET_ACCEPT at the same time
when the latch was already set, let's reconsider that.  We don't want to
run BackgroundWorkerStateChange() and similar PM-signal-processing code
twice as often as before in high load scenarios.

XXX experimental

Reported-by: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGLOcxUa6m7UinPN1gZXFyr92L8btG_pGTHPiWY2YbRw2w%40mail.gmail.com
---
 src/backend/postmaster/postmaster.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index f0f9c66487c..11e7a938f9f 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -1657,7 +1657,8 @@ ServerLoop(void)
 			 * didn't see WL_LATCH_SET.  This gives high priority to shutdown
 			 * and reload requests where the latch happens to appear later in
 			 * events[] or will be reported by a later call to
-			 * WaitEventSetWait().
+			 * WaitEventSetWait().  We also want to release child resources as
+			 * soon as as possible, before accepting sockets.
 			 */
 			if (pending_pm_shutdown_request)
 				process_pm_shutdown_request();
@@ -1665,8 +1666,17 @@ ServerLoop(void)
 				process_pm_reload_request();
 			if (pending_pm_child_exit)
 				process_pm_child_exit();
-			if (pending_pm_pmsignal)
-				process_pm_pmsignal();
+
+			/*
+			 * When receiving high frequency PM signals, we only want to
+			 * process them once per server loop, not once per event of any
+			 * kind.  They are neither very high priority, nor causally linked
+			 * to socket events that might arrive out of order, so we defer
+			 * processing until we see WL_LATCH_SET.
+			 */
+			if (events[i].events & WL_LATCH_SET)
+				if (pending_pm_pmsignal)
+					process_pm_pmsignal();
 
 			if (events[i].events & WL_SOCKET_ACCEPT)
 			{
-- 
2.47.0

