From 52af5ac41c9cf6852ee9d0fceabd9b063b74ddfe Mon Sep 17 00:00:00 2001
From: Nazir Bilal Yavuz <byavuz81@gmail.com>
Date: Thu, 19 Nov 2026 15:03:34 +0300
Subject: [PATCH v1 1/7] Share the walreceiver startup timeout check

WalRcvRunning() and WalRcvStreaming() both check whether the receiver
has taken too long to start. If so, they mark it stopped and wake up
anyone waiting for it to stop.

Move that check into one helper. Each caller still decides for itself
which states count as running or streaming.
---
 src/backend/replication/walreceiverfuncs.c | 63 +++++-----------------
 1 file changed, 14 insertions(+), 49 deletions(-)

diff --git a/src/backend/replication/walreceiverfuncs.c b/src/backend/replication/walreceiverfuncs.c
index ecf510517eb..4175e231ba4 100644
--- a/src/backend/replication/walreceiverfuncs.c
+++ b/src/backend/replication/walreceiverfuncs.c
@@ -71,9 +71,9 @@ WalRcvShmemInit(void *arg)
 	WalRcv->procno = INVALID_PROC_NUMBER;
 }
 
-/* Is walreceiver running (or starting up)? */
-bool
-WalRcvRunning(void)
+/* Return the walreceiver state after checking for a startup timeout. */
+static WalRcvState
+WalRcvGetStateWithTimeout(void)
 {
 	WalRcvData *walrcv = WalRcv;
 	WalRcvState state;
@@ -113,10 +113,14 @@ WalRcvRunning(void)
 		}
 	}
 
-	if (state != WALRCV_STOPPED)
-		return true;
-	else
-		return false;
+	return state;
+}
+
+/* Is walreceiver running (or starting up)? */
+bool
+WalRcvRunning(void)
+{
+	return WalRcvGetStateWithTimeout() != WALRCV_STOPPED;
 }
 
 /* Return the state of the walreceiver. */
@@ -140,49 +144,10 @@ WalRcvGetState(void)
 bool
 WalRcvStreaming(void)
 {
-	WalRcvData *walrcv = WalRcv;
-	WalRcvState state;
-	pg_time_t	startTime;
-
-	SpinLockAcquire(&walrcv->mutex);
-
-	state = walrcv->walRcvState;
-	startTime = walrcv->startTime;
+	WalRcvState state = WalRcvGetStateWithTimeout();
 
-	SpinLockRelease(&walrcv->mutex);
-
-	/*
-	 * If it has taken too long for walreceiver to start up, give up. Setting
-	 * the state to STOPPED ensures that if walreceiver later does start up
-	 * after all, it will see that it's not supposed to be running and die
-	 * without doing anything.
-	 */
-	if (state == WALRCV_STARTING)
-	{
-		pg_time_t	now = (pg_time_t) time(NULL);
-
-		if ((now - startTime) > WALRCV_STARTUP_TIMEOUT)
-		{
-			bool		stopped = false;
-
-			SpinLockAcquire(&walrcv->mutex);
-			if (walrcv->walRcvState == WALRCV_STARTING)
-			{
-				state = walrcv->walRcvState = WALRCV_STOPPED;
-				stopped = true;
-			}
-			SpinLockRelease(&walrcv->mutex);
-
-			if (stopped)
-				ConditionVariableBroadcast(&walrcv->walRcvStoppedCV);
-		}
-	}
-
-	if (state == WALRCV_STREAMING || state == WALRCV_STARTING ||
-		state == WALRCV_CONNECTING || state == WALRCV_RESTARTING)
-		return true;
-	else
-		return false;
+	return state == WALRCV_STREAMING || state == WALRCV_STARTING ||
+		state == WALRCV_CONNECTING || state == WALRCV_RESTARTING;
 }
 
 /*
-- 
2.47.3

