From 09cde16331658cbb18ca5adc90fee767e0bff0a3 Mon Sep 17 00:00:00 2001
From: Yura Sokolov <y.sokolov@postgrespro.ru>
Date: Sun, 6 Dec 2026 17:16:48 +0300
Subject: [PATCH v1 2/8] pgbench: rework client bookkeeping in the thread event
 loop
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Make the per-iteration cost of threadRun() proportional to the number of
clients with work to do, not to the thread's client count.

* advanceConnectionState() maintains the socket_set registration itself:
  CState.sockidx holds the client's slot in the set (or -1 when it is
  not registered); a client joins the set when it starts a command and
  leaves it when it parks in the wakeup heap or disconnects, so the set
  is no longer rebuilt and scanned on every iteration;

* sleeping and throttled clients are parked in a pairing heap keyed by
  wakeup time (CState.phnode/when); threadRun() peeks at its root for
  the nearest wakeup instead of scanning all clients, and pops the
  clients whose time has come after the wait;

* clients to run are collected in a singly-linked ready list; those
  freed by the wakeup heap are added there, and wait_on_socket_set()
  enqueues the clients that came back ready itself, so no code path
  scans clients without work.

State shared by all clients of a thread run — the socket set, the
wakeup heap, the aggregation-interval stats, the ready list and the
lazily obtained current time — is gathered into a RunState struct local
to threadRun() and passed down to the routines advancing clients,
instead of the whole TState and extra per-call arguments; the current
time now lives in RunState, and pg_time_now_lazy() takes it and returns
the time.

This simplifies the code and makes it easier to add the asynchronous
connection and query preparation features on top.
---
 src/backend/lib/meson.build               |   1 -
 src/bin/pgbench/pgbench.c                 | 708 ++++++++++++++--------
 src/common/meson.build                    |   1 +
 src/{backend/lib => common}/pairingheap.c |   6 +-
 src/tools/pgindent/typedefs.list          |   1 +
 5 files changed, 457 insertions(+), 260 deletions(-)
 rename src/{backend/lib => common}/pairingheap.c (98%)

diff --git a/src/backend/lib/meson.build b/src/backend/lib/meson.build
index 8e38fb20f17..f9ab27e6a9e 100644
--- a/src/backend/lib/meson.build
+++ b/src/backend/lib/meson.build
@@ -8,6 +8,5 @@ backend_sources += files(
   'ilist.c',
   'integerset.c',
   'knapsack.c',
-  'pairingheap.c',
   'rbtree.c',
 )
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index b13d4996688..2b1c7a6dd12 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -64,6 +64,7 @@
 #include "fe_utils/option_utils.h"
 #include "fe_utils/string_utils.h"
 #include "getopt_long.h"
+#include "lib/pairingheap.h"
 #include "libpq-fe.h"
 #include "pgbench.h"
 #include "port/pg_bitutils.h"
@@ -91,6 +92,8 @@
  * Multi-platform socket set implementations
  */
 
+typedef struct CState CState;
+
 #ifdef POLL_USING_PPOLL
 #define SOCKET_WAIT_METHOD "ppoll"
 
@@ -98,7 +101,9 @@ typedef struct socket_set
 {
 	int			maxfds;			/* allocated length of pollfds[] array */
 	int			curfds;			/* number currently in use */
-	pg_attribute_counted_by(maxfds) struct pollfd pollfds[FLEXIBLE_ARRAY_MEMBER];
+	CState	  **states;			/* same length as pollfds; states[i] is the
+								 * CState whose socket is in pollfds[i] */
+	struct pollfd *pollfds;
 } socket_set;
 
 #endif							/* POLL_USING_PPOLL */
@@ -109,7 +114,10 @@ typedef struct socket_set
 typedef struct socket_set
 {
 	int			maxfd;			/* largest FD currently set in fds */
-	fd_set		fds;
+	int			maxfds;			/* allocated length of states[] array */
+	int			curfds;			/* number of sockets currently in the set */
+	fd_set		fds;			/* registration set: sockets we are waiting on */
+	CState	  **states;			/* maps slot index (0..curfds-1) to CState */
 } socket_set;
 
 #endif							/* POLL_USING_SELECT */
@@ -602,7 +610,7 @@ typedef enum
 /*
  * Connection state.
  */
-typedef struct
+struct CState
 {
 	PGconn	   *con;			/* connection handle to DB */
 	int			id;				/* client No. */
@@ -646,7 +654,16 @@ typedef struct
 	int64		cnt;			/* client transaction count, for -t; skipped
 								 * and failed transactions are also counted
 								 * here */
-} CState;
+
+	int			sockidx;		/* index in socket_set while waiting for
+								 * input; -1 when not present in the set */
+
+	pairingheap_node phnode;	/* heap node for sleep/throttle wakeup */
+	pg_time_usec_t when;		/* wakeup time (key for the heap) */
+
+	struct CState *next_ready;	/* next client in the thread's ready list */
+	bool		is_ready;		/* this client is in ready list */
+};
 
 /*
  * Thread state
@@ -681,6 +698,33 @@ typedef struct
 	int64		latency_late;	/* count executed but late transactions */
 } TState;
 
+/*
+ * Thread-run state, local to threadRun() and passed down to the routines
+ * advancing clients, instead of the whole TState.  'thread' is kept here for
+ * routines that also need the rest of the thread state.
+ */
+typedef struct RunState
+{
+	TState	   *thread;			/* thread this state belongs to */
+	socket_set *sockets;		/* sockets the thread waits on */
+
+	pairingheap wakeup_heap;	/* pairing heap of sleeping/throttled clients */
+
+	StatsData	aggs;			/* aggregation-interval stats */
+
+	/* list of clients ready to run (not waiting for I/O, sleep, or throttle) */
+	CState	   *ready;			/* head of singly-linked ready list */
+
+	/*
+	 * gettimeofday() isn't free, so the current time is obtained lazily by
+	 * pg_time_now_lazy() the first time it is needed, and reused afterwards.
+	 * Zero means "not set yet".  It is reset after establishing a connection
+	 * or executing a shell command or expression, which might have taken a
+	 * non-negligible amount of time, and refreshed after each wait.
+	 */
+	pg_time_usec_t now;
+} RunState;
+
 /*
  * queries read from files
  */
@@ -833,21 +877,23 @@ static void setIntValue(PgBenchValue *pv, int64 ival);
 static void setDoubleValue(PgBenchValue *pv, double dval);
 static bool evaluateExpr(CState *st, PgBenchExpr *expr,
 						 PgBenchValue *retval);
-static ConnectionStateEnum executeMetaCommand(CState *st, pg_time_usec_t *now);
-static void doLog(TState *thread, CState *st,
-				  StatsData *agg, bool tx_skipped, double latency, double lag);
-static void processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
-							 bool tx_skipped, StatsData *agg);
+static ConnectionStateEnum executeMetaCommand(RunState *run, CState *st);
+static void doLog(RunState *run, CState *st,
+				  bool tx_skipped, double latency, double lag);
+static void processXactStats(RunState *run, CState *st, bool tx_skipped);
 static void addScript(const ParsedScript *script);
 static THREAD_FUNC_RETURN_TYPE THREAD_FUNC_CC threadRun(void *arg);
-static void finishCon(CState *st);
+static void finishCon(socket_set *sockets, CState *st);
 static void setalarm(int seconds);
 static socket_set *alloc_socket_set(int count);
 static void free_socket_set(socket_set *sa);
-static void clear_socket_set(socket_set *sa);
-static void add_socket_to_set(socket_set *sa, int fd, int idx);
-static int	wait_on_socket_set(socket_set *sa, int64 usecs);
-static bool socket_has_input(socket_set *sa, int fd, int idx);
+static void add_socket_to_set(socket_set *sa, CState *st);
+static void remove_socket_from_set(socket_set *sa, CState *st);
+static int	wait_on_socket_set(RunState *run, int64 usecs);
+
+static int	wakeup_heap_compare(const pairingheap_node *a, const pairingheap_node *b, void *arg);
+static void wakeup_heap_insert(pairingheap *heap, CState *st, pg_time_usec_t when);
+static pg_time_usec_t wakeup_heap_peek_min(pairingheap *heap);
 
 /* callback used to build rows for COPY during data loading */
 typedef void (*initRowMethod) (PQExpBufferData *sql, int64 curr);
@@ -892,11 +938,13 @@ pg_time_now(void)
 	return (pg_time_usec_t) INSTR_TIME_GET_MICROSEC(now);
 }
 
-static inline void
-pg_time_now_lazy(pg_time_usec_t *now)
+static inline pg_time_usec_t
+pg_time_now_lazy(RunState *run)
 {
-	if ((*now) == 0)
-		(*now) = pg_time_now();
+	if (run->now == 0)
+		run->now = pg_time_now();
+
+	return run->now;
 }
 
 #define PG_TIME_GET_DOUBLE(t) (0.000001 * (t))
@@ -3488,7 +3536,7 @@ evaluateSleep(Variables *variables, int argc, char **argv, int *usecs)
  * Returns true if the error can be retried.
  */
 static bool
-doRetry(CState *st, pg_time_usec_t *now)
+doRetry(RunState *run, CState *st)
 {
 	Assert(st->estatus != ESTATUS_NO_ERROR);
 
@@ -3515,8 +3563,7 @@ doRetry(CState *st, pg_time_usec_t *now)
 	 */
 	if (latency_limit)
 	{
-		pg_time_now_lazy(now);
-		if (*now - st->txn_scheduled > latency_limit)
+		if (pg_time_now_lazy(run) - st->txn_scheduled > latency_limit)
 			return false;
 	}
 
@@ -3641,7 +3688,7 @@ getTransactionStatus(PGconn *con)
  * Print verbose messages of an error
  */
 static void
-printVerboseErrorMessages(CState *st, pg_time_usec_t *now, bool is_retry)
+printVerboseErrorMessages(RunState *run, CState *st, bool is_retry)
 {
 	PQExpBufferData buf;
 
@@ -3663,9 +3710,9 @@ printVerboseErrorMessages(CState *st, pg_time_usec_t *now, bool is_retry)
 	 */
 	if (latency_limit)
 	{
-		pg_time_now_lazy(now);
 		appendPQExpBuffer(&buf, ", %.3f%% of the maximum time of tries was used",
-						  (100.0 * (*now - st->txn_scheduled) / latency_limit));
+						  100.0 *
+						  (pg_time_now_lazy(run) - st->txn_scheduled) / latency_limit);
 	}
 	appendPQExpBufferStr(&buf, ")\n");
 
@@ -3674,23 +3721,36 @@ printVerboseErrorMessages(CState *st, pg_time_usec_t *now, bool is_retry)
 	termPQExpBuffer(&buf);
 }
 
+/*
+ * Is a given state "active" (i.e., the client is ready to act and not
+ * sleeping, throttled, waiting for I/O, or done)?
+ */
+#define STATE_IS_ACTIVE(s) \
+	((s) != CSTATE_SLEEP && (s) != CSTATE_THROTTLE && \
+	 (s) != CSTATE_WAIT_RESULT && (s) != CSTATE_WAIT_ROLLBACK_RESULT && \
+	 (s) != CSTATE_ABORTED && (s) != CSTATE_FINISHED)
+
+/*
+ * Add a client to the thread's ready list (those ready to run).
+ * The ready list is a singly-linked list using CState.next_ready.
+ */
+static void
+ready_add(RunState *run, CState *st)
+{
+	if (st->is_ready)
+		return;
+
+	st->is_ready = true;
+	st->next_ready = run->ready;
+	run->ready = st;
+}
+
 /*
  * Advance the state machine of a connection.
  */
 static void
-advanceConnectionState(TState *thread, CState *st, StatsData *agg)
+advanceConnectionState(RunState *run, CState *st)
 {
-
-	/*
-	 * gettimeofday() isn't free, so we get the current timestamp lazily the
-	 * first time it's needed, and reuse the same value throughout this
-	 * function after that.  This also ensures that e.g. the calculated
-	 * latency reported in the log file and in the totals are the same. Zero
-	 * means "not set yet".  Reset "now" when we execute shell commands or
-	 * expressions, which might take a non-negligible amount of time, though.
-	 */
-	pg_time_usec_t now = 0;
-
 	/*
 	 * Loop in the state machine, until we have to wait for a result from the
 	 * server or have to sleep for throttling or \sleep.
@@ -3708,7 +3768,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 		{
 				/* Select transaction (script) to run.  */
 			case CSTATE_CHOOSE_SCRIPT:
-				st->use_file = chooseScript(thread);
+				st->use_file = chooseScript(run->thread);
 				Assert(conditional_stack_empty(st->cstack));
 
 				/* reset transaction variables to default values */
@@ -3728,12 +3788,10 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 
 				/* Start new transaction (script) */
 			case CSTATE_START_TX:
-				pg_time_now_lazy(&now);
-
 				/* establish connection if needed, i.e. under --connect */
 				if (st->con == NULL)
 				{
-					pg_time_usec_t start = now;
+					pg_time_usec_t start = pg_time_now_lazy(run);
 
 					if ((st->con = doConnect()) == NULL)
 					{
@@ -3747,9 +3805,9 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 					}
 
 					/* reset now after connection */
-					now = pg_time_now();
+					run->now = pg_time_now();
 
-					thread->conn_duration += now - start;
+					run->thread->conn_duration += run->now - start;
 
 					/* Reset session-local state */
 					pg_free(st->prepared);
@@ -3764,14 +3822,14 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				st->random_state = st->cs_func_rs;
 
 				/* record transaction start time */
-				st->txn_begin = now;
+				st->txn_begin = pg_time_now_lazy(run);
 
 				/*
 				 * When not throttling, this is also the transaction's
 				 * scheduled start time.
 				 */
 				if (!throttle_delay)
-					st->txn_scheduled = now;
+					st->txn_scheduled = run->now;
 
 				/* Begin with the first command */
 				st->state = CSTATE_START_COMMAND;
@@ -3794,9 +3852,9 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 */
 				Assert(throttle_delay > 0);
 
-				thread->throttle_trigger +=
-					getPoissonRand(&thread->ts_throttle_rs, throttle_delay);
-				st->txn_scheduled = thread->throttle_trigger;
+				run->thread->throttle_trigger +=
+					getPoissonRand(&run->thread->ts_throttle_rs, throttle_delay);
+				st->txn_scheduled = run->thread->throttle_trigger;
 
 				/*
 				 * If --latency-limit is used, and this slot is already late
@@ -3806,11 +3864,9 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 */
 				if (latency_limit)
 				{
-					pg_time_now_lazy(&now);
-
-					if (thread->throttle_trigger < now - latency_limit)
+					if (run->thread->throttle_trigger < pg_time_now_lazy(run) - latency_limit)
 					{
-						processXactStats(thread, st, &now, true, agg);
+						processXactStats(run, st, true);
 
 						/*
 						 * Finish client if -T or -t was exceeded.
@@ -3839,19 +3895,28 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 * stop client if next transaction is beyond pgbench end of
 				 * execution; otherwise, throttle it.
 				 */
-				st->state = end_time > 0 && st->txn_scheduled > end_time ?
-					CSTATE_FINISHED : CSTATE_THROTTLE;
+				if (end_time > 0 && st->txn_scheduled > end_time)
+				{
+					st->state = CSTATE_FINISHED;
+				}
+				else if (st->txn_scheduled <= pg_time_now_lazy(run))
+				{
+					st->state = CSTATE_START_TX;
+					break;
+				}
+				else
+				{
+					st->state = CSTATE_THROTTLE;
+					wakeup_heap_insert(&run->wakeup_heap, st, st->txn_scheduled);
+					remove_socket_from_set(run->sockets, st);
+					return;
+				}
 				break;
 
 				/*
 				 * Wait until it's time to start next transaction.
 				 */
 			case CSTATE_THROTTLE:
-				pg_time_now_lazy(&now);
-
-				if (now < st->txn_scheduled)
-					return;		/* still sleeping, nothing to do here */
-
 				/* done sleeping, but don't start transaction if we're done */
 				st->state = timer_exceeded ? CSTATE_FINISHED : CSTATE_START_TX;
 				break;
@@ -3860,6 +3925,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 * Send a command to server (or execute a meta-command)
 				 */
 			case CSTATE_START_COMMAND:
+				add_socket_to_set(run->sockets, st);
 				command = sql_script[st->use_file].commands[st->command];
 
 				/*
@@ -3883,8 +3949,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				/* record begin time of next command, and initiate it */
 				if (report_per_command)
 				{
-					pg_time_now_lazy(&now);
-					st->stmt_begin = now;
+					st->stmt_begin = pg_time_now_lazy(run);
 				}
 
 				/* Execute the command */
@@ -3917,6 +3982,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 						/* Wait for results, unless in pipeline mode */
 						if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
 							st->state = CSTATE_WAIT_RESULT;
+
 						else
 							st->state = CSTATE_END_COMMAND;
 					}
@@ -3929,7 +3995,14 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 					 * - on sleep CSTATE_SLEEP
 					 * - else CSTATE_END_COMMAND
 					 */
-					st->state = executeMetaCommand(st, &now);
+					st->state = executeMetaCommand(run, st);
+
+					if (st->state == CSTATE_SLEEP)
+					{
+						wakeup_heap_insert(&run->wakeup_heap, st, st->sleep_until);
+						remove_socket_from_set(run->sockets, st);
+						return;
+					}
 					if (st->state == CSTATE_ABORTED)
 						st->estatus = ESTATUS_META_COMMAND_ERROR;
 				}
@@ -4090,10 +4163,6 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 * instead of CSTATE_START_TX.
 				 */
 			case CSTATE_SLEEP:
-				pg_time_now_lazy(&now);
-				if (now < st->sleep_until)
-					return;		/* still sleeping, nothing to do here */
-				/* Else done sleeping. */
 				st->state = CSTATE_END_COMMAND;
 				break;
 
@@ -4109,7 +4178,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 */
 				if (report_per_command)
 				{
-					pg_time_now_lazy(&now);
+					pg_time_usec_t now = pg_time_now_lazy(run);
 
 					command = sql_script[st->use_file].commands[st->command];
 					/* XXX could use a mutex here, but we choose not to */
@@ -4169,7 +4238,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 						 * can retry the error.
 						 */
 						st->state = timer_exceeded ? CSTATE_FINISHED :
-							doRetry(st, &now) ? CSTATE_RETRY : CSTATE_FAILURE;
+							doRetry(run, st) ? CSTATE_RETRY : CSTATE_FAILURE;
 					}
 					else
 					{
@@ -4218,7 +4287,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 							 * if we can retry the error.
 							 */
 							st->state = timer_exceeded ? CSTATE_FINISHED :
-								doRetry(st, &now) ? CSTATE_RETRY : CSTATE_FAILURE;
+								doRetry(run, st) ? CSTATE_RETRY : CSTATE_FAILURE;
 							break;
 						default:
 							pg_log_error("client %d aborted while rolling back the transaction after an error; %s",
@@ -4241,7 +4310,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 * error.
 				 */
 				if (verbose_errors)
-					printVerboseErrorMessages(st, &now, true);
+					printVerboseErrorMessages(run, st, true);
 
 				/* Count tries and retries */
 				st->tries++;
@@ -4272,7 +4341,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 * Inform that the failed transaction will not be retried.
 				 */
 				if (verbose_errors)
-					printVerboseErrorMessages(st, &now, false);
+					printVerboseErrorMessages(run, st, false);
 
 				/* End the failed transaction. */
 				st->state = CSTATE_END_TX;
@@ -4286,7 +4355,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 					TStatus		tstatus;
 
 					/* transaction finished: calculate latency and do log */
-					processXactStats(thread, st, &now, false, agg);
+					processXactStats(run, st, false);
 
 					/*
 					 * missing \endif... cannot happen if CheckConditional was
@@ -4318,12 +4387,11 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 
 					if (is_connect)
 					{
-						pg_time_usec_t start = now;
+						pg_time_usec_t start = pg_time_now_lazy(run);
 
-						pg_time_now_lazy(&start);
-						finishCon(st);
-						now = pg_time_now();
-						thread->conn_duration += now - start;
+						finishCon(run->sockets, st);
+						run->now = pg_time_now();
+						run->thread->conn_duration += run->now - start;
 					}
 
 					if ((st->cnt >= nxacts && duration <= 0) || timer_exceeded)
@@ -4362,7 +4430,7 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
 				 * necessary because we cannot report complete results anyways
 				 * in this case.
 				 */
-				finishCon(st);
+				finishCon(run->sockets, st);
 				return;
 		}
 	}
@@ -4372,11 +4440,11 @@ advanceConnectionState(TState *thread, CState *st, StatsData *agg)
  * Subroutine for advanceConnectionState -- initiate or execute the current
  * meta command, and return the next state to set.
  *
- * *now is updated to the current time, unless the command is expected to
- * take no time to execute.
+ * run->now is updated to the current time, unless the command is expected
+ * to take no time to execute.
  */
 static ConnectionStateEnum
-executeMetaCommand(CState *st, pg_time_usec_t *now)
+executeMetaCommand(RunState *run, CState *st)
 {
 	Command    *command = sql_script[st->use_file].commands[st->command];
 	int			argc;
@@ -4418,8 +4486,7 @@ executeMetaCommand(CState *st, pg_time_usec_t *now)
 			return CSTATE_ABORTED;
 		}
 
-		pg_time_now_lazy(now);
-		st->sleep_until = (*now) + usec;
+		st->sleep_until = pg_time_now_lazy(run) + usec;
 		return CSTATE_SLEEP;
 	}
 	else if (command->meta == META_SET)
@@ -4586,7 +4653,7 @@ executeMetaCommand(CState *st, pg_time_usec_t *now)
 	 * executing the expression or shell command might have taken a
 	 * non-negligible amount of time, so reset 'now'
 	 */
-	*now = 0;
+	run->now = 0;
 
 	return CSTATE_END_COMMAND;
 }
@@ -4640,10 +4707,11 @@ getResultString(bool tx_skipped, EStatus estatus)
  * avoid the cost of an extra call to pg_time_now().
  */
 static void
-doLog(TState *thread, CState *st,
-	  StatsData *agg, bool tx_skipped, double latency, double lag)
+doLog(RunState *run, CState *st,
+	  bool tx_skipped, double latency, double lag)
 {
-	FILE	   *logfile = thread->logfile;
+	FILE	   *logfile = run->thread->logfile;
+	StatsData  *agg = &run->aggs;
 	pg_time_usec_t now = pg_time_now() + epoch_shift;
 
 	Assert(use_log);
@@ -4653,7 +4721,7 @@ doLog(TState *thread, CState *st,
 	 * to the random sample.
 	 */
 	if (sample_rate != 0.0 &&
-		pg_prng_double(&thread->ts_sample_rs) > sample_rate)
+		pg_prng_double(&run->thread->ts_sample_rs) > sample_rate)
 		return;
 
 	/* should we aggregate the results or not? */
@@ -4763,8 +4831,7 @@ doLog(TState *thread, CState *st,
  * "cnt" field.)
  */
 static void
-processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
-				 bool tx_skipped, StatsData *agg)
+processXactStats(RunState *run, CState *st, bool tx_skipped)
 {
 	double		latency = 0.0,
 				lag = 0.0;
@@ -4773,25 +4840,23 @@ processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
 
 	if (detailed && !tx_skipped && st->estatus == ESTATUS_NO_ERROR)
 	{
-		pg_time_now_lazy(now);
-
 		/* compute latency & lag */
-		latency = (*now) - st->txn_scheduled;
+		latency = pg_time_now_lazy(run) - st->txn_scheduled;
 		lag = st->txn_begin - st->txn_scheduled;
 	}
 
 	/* keep detailed thread stats */
-	accumStats(&thread->stats, tx_skipped, latency, lag, st->estatus, st->tries);
+	accumStats(&run->thread->stats, tx_skipped, latency, lag, st->estatus, st->tries);
 
 	/* count transactions over the latency limit, if needed */
 	if (latency_limit && latency > latency_limit)
-		thread->latency_late++;
+		run->thread->latency_late++;
 
 	/* client stat is just counting */
 	st->cnt++;
 
 	if (use_log)
-		doLog(thread, st, agg, tx_skipped, latency, lag);
+		doLog(run, st, tx_skipped, latency, lag);
 
 	/* XXX could use a mutex here, but we choose not to */
 	if (per_script_stats)
@@ -4802,12 +4867,12 @@ processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
 
 /* discard connections */
 static void
-disconnect_all(CState *state, int length)
+disconnect_all(socket_set *sockets, CState *state, int length)
 {
 	int			i;
 
 	for (i = 0; i < length; i++)
-		finishCon(&state[i]);
+		finishCon(sockets, &state[i]);
 }
 
 /*
@@ -7564,7 +7629,7 @@ main(int argc, char **argv)
 	 * disconnect_all() will be a no-op, but clean up the connections just to
 	 * be sure. We don't need to measure the disconnection delays here.
 	 */
-	disconnect_all(state, nclients);
+	disconnect_all(NULL, state, nclients);
 
 	/*
 	 * Beware that performance of short benchmarks with many threads and
@@ -7592,12 +7657,15 @@ threadRun(void *arg)
 	pg_time_usec_t start;
 	int			nstate = thread->nstate;
 	int			remains = nstate;	/* number of remaining clients */
-	socket_set *sockets = alloc_socket_set(nstate);
 	int64		thread_start,
 				last_report,
 				next_report;
-	StatsData	last,
-				aggs;
+	StatsData	last;
+	RunState	run;
+
+	run.thread = thread;
+	run.sockets = alloc_socket_set(nstate);
+	pairingheap_initialize(&run.wakeup_heap, wakeup_heap_compare, NULL);
 
 	/* open log file if requested */
 	if (use_log)
@@ -7617,8 +7685,13 @@ threadRun(void *arg)
 	}
 
 	/* explicitly initialize the state machines */
+	run.ready = NULL;
 	for (int i = 0; i < nstate; i++)
+	{
 		state[i].state = CSTATE_CHOOSE_SCRIPT;
+		state[i].sockidx = -1;
+		ready_add(&run, &state[i]);
+	}
 
 	/* READY */
 	THREAD_BARRIER_WAIT(&barrier);
@@ -7647,7 +7720,7 @@ threadRun(void *arg)
 	/* GO */
 	THREAD_BARRIER_WAIT(&barrier);
 
-	start = pg_time_now();
+	run.now = start = pg_time_now();
 	thread->bench_start = start;
 	thread->throttle_trigger = start;
 
@@ -7658,79 +7731,43 @@ threadRun(void *arg)
 	 * fraction of a second later, but later aggregates are measured from the
 	 * whole number time that is actually logged).
 	 */
-	initStats(&aggs, (start + epoch_shift) / 1000000 * 1000000);
-	last = aggs;
+	initStats(&run.aggs, (start + epoch_shift) / 1000000 * 1000000);
+	last = run.aggs;
 
 	/* loop till all clients have terminated */
 	while (remains > 0)
 	{
-		int			nsocks;		/* number of sockets to be waited for */
 		pg_time_usec_t min_usec;
-		pg_time_usec_t now = 0; /* set this only if needed */
+		CState	   *ready;
 
 		/*
-		 * identify which client sockets should be checked for input, and
-		 * compute the nearest time (if any) at which we need to wake up.
+		 * Compute the nearest time (if any) at which we need to wake up. The
+		 * socket set is maintained by advanceConnectionState, so we only need
+		 * to consider sleep/throttle timers here.
+		 *
+		 * If any client is ready to run (in the ready list), we must not
+		 * wait.
 		 */
-		clear_socket_set(sockets);
-		nsocks = 0;
-		min_usec = PG_INT64_MAX;
-		for (int i = 0; i < nstate; i++)
+		if (run.ready != NULL)
+			min_usec = 0;
+		else if (!pairingheap_is_empty(&run.wakeup_heap))
 		{
-			CState	   *st = &state[i];
+			pg_time_usec_t heap_min = wakeup_heap_peek_min(&run.wakeup_heap);
 
-			if (st->state == CSTATE_SLEEP || st->state == CSTATE_THROTTLE)
-			{
-				/* a nap from the script, or under throttling */
-				pg_time_usec_t this_usec;
-
-				/* get current time if needed */
-				pg_time_now_lazy(&now);
-
-				/* min_usec should be the minimum delay across all clients */
-				this_usec = (st->state == CSTATE_SLEEP ?
-							 st->sleep_until : st->txn_scheduled) - now;
-				if (min_usec > this_usec)
-					min_usec = this_usec;
-			}
-			else if (st->state == CSTATE_WAIT_RESULT ||
-					 st->state == CSTATE_WAIT_ROLLBACK_RESULT)
-			{
-				/*
-				 * waiting for result from server - nothing to do unless the
-				 * socket is readable
-				 */
-				int			sock = PQsocket(st->con);
-
-				if (sock < 0)
-				{
-					pg_log_error("invalid socket: %s", PQerrorMessage(st->con));
-					goto done;
-				}
-
-				add_socket_to_set(sockets, sock, nsocks++);
-			}
-			else if (st->state != CSTATE_ABORTED &&
-					 st->state != CSTATE_FINISHED)
-			{
-				/*
-				 * This client thread is ready to do something, so we don't
-				 * want to wait.  No need to examine additional clients.
-				 */
+			min_usec = heap_min - run.now;
+			if (min_usec < 0)
 				min_usec = 0;
-				break;
-			}
 		}
+		else
+			min_usec = PG_INT64_MAX;
 
 		/* also wake up to print the next progress report on time */
 		if (progress && min_usec > 0 && thread->tid == 0)
 		{
-			pg_time_now_lazy(&now);
-
-			if (now >= next_report)
+			if (run.now >= next_report)
 				min_usec = 0;
-			else if ((next_report - now) < min_usec)
-				min_usec = next_report - now;
+			else if ((next_report - run.now) < min_usec)
+				min_usec = next_report - run.now;
 		}
 
 		/*
@@ -7743,9 +7780,9 @@ threadRun(void *arg)
 
 			if (min_usec != PG_INT64_MAX)
 			{
-				if (nsocks > 0)
+				if (run.sockets->curfds > 0)
 				{
-					rc = wait_on_socket_set(sockets, min_usec);
+					rc = wait_on_socket_set(&run, min_usec);
 				}
 				else			/* nothing active, simple sleep */
 				{
@@ -7754,7 +7791,7 @@ threadRun(void *arg)
 			}
 			else				/* no explicit delay, wait without timeout */
 			{
-				rc = wait_on_socket_set(sockets, 0);
+				rc = wait_on_socket_set(&run, 0);
 			}
 
 			if (rc < 0)
@@ -7768,67 +7805,78 @@ threadRun(void *arg)
 				pg_log_error("%s() failed: %m", SOCKET_WAIT_METHOD);
 				goto done;
 			}
-		}
-		else
-		{
-			/* min_usec <= 0, i.e. something needs to be executed now */
 
-			/* If we didn't wait, don't try to read any data */
-			clear_socket_set(sockets);
+			run.now = pg_time_now();
 		}
 
-		/* ok, advance the state machine of each connection */
-		nsocks = 0;
-		for (int i = 0; i < nstate; i++)
+		/*
+		 * Move any clients whose wakeup time has arrived from the pairing
+		 * heap to the ready list.
+		 */
+		if (!pairingheap_is_empty(&run.wakeup_heap))
 		{
-			CState	   *st = &state[i];
-
-			if (st->state == CSTATE_WAIT_RESULT ||
-				st->state == CSTATE_WAIT_ROLLBACK_RESULT)
+			while (!pairingheap_is_empty(&run.wakeup_heap))
 			{
-				/* don't call advanceConnectionState unless data is available */
-				int			sock = PQsocket(st->con);
+				pg_time_usec_t heap_min = wakeup_heap_peek_min(&run.wakeup_heap);
 
-				if (sock < 0)
+				if (heap_min > run.now)
+					break;
+
+				/* pop the client and add to ready list */
 				{
-					pg_log_error("invalid socket: %s", PQerrorMessage(st->con));
-					goto done;
+					pairingheap_node *node = pairingheap_remove_first(&run.wakeup_heap);
+					CState	   *st = pairingheap_container(CState, phnode, node);
+
+					ready_add(&run, st);
 				}
-
-				if (!socket_has_input(sockets, sock, nsocks++))
-					continue;
-			}
-			else if (st->state == CSTATE_FINISHED ||
-					 st->state == CSTATE_ABORTED)
-			{
-				/* this client is done, no need to consider it anymore */
-				continue;
 			}
+		}
 
-			advanceConnectionState(thread, st, &aggs);
+		/*
+		 * Process all clients that are ready to run.  We detach the ready
+		 * list from the thread and walk it.  While advancing clients, new
+		 * clients may be added to run.ready; those will be processed in the
+		 * next iteration of the threadRun loop.
+		 */
+		ready = run.ready;
+		run.ready = NULL;
+
+		while (ready != NULL)
+		{
+			CState	   *next = ready->next_ready;
+
+			ready->is_ready = false;
+
+			advanceConnectionState(&run, ready);
 
 			/*
 			 * If --exit-on-abort is used, the program is going to exit when
 			 * any client is aborted.
 			 */
-			if (exit_on_abort && st->state == CSTATE_ABORTED)
+			if (exit_on_abort && ready->state == CSTATE_ABORTED)
 				goto done;
 
 			/*
 			 * If advanceConnectionState changed client to finished state,
 			 * that's one fewer client that remains.
 			 */
-			else if (st->state == CSTATE_FINISHED ||
-					 st->state == CSTATE_ABORTED)
+			else if (ready->state == CSTATE_FINISHED ||
+					 ready->state == CSTATE_ABORTED)
 				remains--;
+			else if (STATE_IS_ACTIVE(ready->state))
+				/* client is still active, so it needs to be processed */
+				ready_add(&run, ready);
+
+			ready = next;
 		}
 
+		run.now = pg_time_now();
+
 		/* progress report is made by thread 0 for all threads */
 		if (progress && thread->tid == 0)
 		{
-			pg_time_usec_t now2 = pg_time_now();
 
-			if (now2 >= next_report)
+			if (run.now >= next_report)
 			{
 				/*
 				 * Horrible hack: this relies on the thread pointer we are
@@ -7836,7 +7884,7 @@ threadRun(void *arg)
 				 * entry of the threads array.  That is why this MUST be done
 				 * by thread 0 and not any other.
 				 */
-				printProgressReport(thread, thread_start, now2,
+				printProgressReport(thread, thread_start, run.now,
 									&last, &last_report);
 
 				/*
@@ -7846,7 +7894,7 @@ threadRun(void *arg)
 				do
 				{
 					next_report += (int64) (1000000.0 * progress);
-				} while (now2 >= next_report);
+				} while (run.now >= next_report);
 			}
 		}
 	}
@@ -7868,32 +7916,74 @@ done:
 		}
 	}
 
-	disconnect_all(state, nstate);
+	disconnect_all(run.sockets, state, nstate);
 
 	if (thread->logfile)
 	{
 		if (agg_interval > 0)
 		{
 			/* log aggregated but not yet reported transactions */
-			doLog(thread, state, &aggs, false, 0, 0);
+			doLog(&run, state, false, 0, 0);
 		}
 		fclose(thread->logfile);
 		thread->logfile = NULL;
 	}
-	free_socket_set(sockets);
+	free_socket_set(run.sockets);
 	THREAD_FUNC_RETURN;
 }
 
 static void
-finishCon(CState *st)
+finishCon(socket_set *sockets, CState *st)
 {
 	if (st->con != NULL)
 	{
+		if (sockets)
+			remove_socket_from_set(sockets, st);
 		PQfinish(st->con);
 		st->con = NULL;
 	}
 }
 
+/*
+ * Comparison function for the wakeup heap.  We want a min-heap on the
+ * wakeup time (when).
+ */
+static int
+wakeup_heap_compare(const pairingheap_node *a, const pairingheap_node *b, void *arg)
+{
+	const CState *ca = pairingheap_const_container(CState, phnode, a);
+	const CState *cb = pairingheap_const_container(CState, phnode, b);
+
+	if (ca->when < cb->when)
+		return -1;
+	else if (ca->when > cb->when)
+		return 1;
+	return 0;
+}
+
+/*
+ * Insert a client into the wakeup heap.  st must not already be in the heap.
+ */
+static void
+wakeup_heap_insert(pairingheap *heap, CState *st, pg_time_usec_t when)
+{
+	st->when = when;
+	pairingheap_add(heap, &st->phnode);
+}
+
+/*
+ * Peek at the minimum wakeup time without removing it.
+ * Returns PG_INT64_MAX if the heap is empty.
+ */
+static pg_time_usec_t
+wakeup_heap_peek_min(pairingheap *heap)
+{
+	if (heap == NULL || heap->ph_root == NULL)
+		return PG_INT64_MAX;
+
+	return pairingheap_container(CState, phnode, pairingheap_first(heap))->when;
+}
+
 /*
  * Support for duration option: set timer_exceeded after so many seconds.
  */
@@ -7956,22 +8046,20 @@ setalarm(int seconds)
  *
  * free_socket_set: deallocate a socket set.
  *
- * clear_socket_set: reset a socket set to empty.
+ * add_socket_to_set: add the client's socket to the set, placing it in
+ *		slot sa->curfds; sets st->sockidx to that slot.
  *
- * add_socket_to_set: add socket with indicated FD to slot "idx" in the
- *		socket set.  Slots must be filled in order, starting with 0.
+ * remove_socket_from_set: remove the client and its socket from the set;
+ *		sets st->sockidx to -1.
  *
  * wait_on_socket_set: wait for input on any socket in set, or for timeout
  *		to expire.  timeout is measured in microseconds; 0 means wait forever.
  *		Returns result code of underlying syscall (>=0 if OK, else see errno).
+ *		Calls ready_add for each socket that is ready.
  *
- * socket_has_input: after waiting, call this to see if given socket has
- *		input.  fd and idx parameters should match some previous call to
- *		add_socket_to_set.
- *
- * Note that wait_on_socket_set destructively modifies the state of the
- * socket set.  After checking for input, caller must apply clear_socket_set
- * and add_socket_to_set again before waiting again.
+ * The socket set is maintained incrementally by advanceConnectionState.
+ * A CState's sockidx field holds its slot index while it is registered
+ * in the set, and -1 otherwise.
  */
 
 #ifdef POLL_USING_PPOLL
@@ -7981,68 +8069,109 @@ alloc_socket_set(int count)
 {
 	socket_set *sa;
 
-	sa = (socket_set *) pg_malloc0(offsetof(socket_set, pollfds) +
-								   sizeof(struct pollfd) * count);
+	sa = pg_malloc0_object(socket_set);
 	sa->maxfds = count;
 	sa->curfds = 0;
+	sa->pollfds = pg_malloc0_array(struct pollfd, count);
+	sa->states = pg_malloc0_array(CState *, count);
 	return sa;
 }
 
 static void
 free_socket_set(socket_set *sa)
 {
+	pg_free(sa->pollfds);
+	pg_free(sa->states);
 	pg_free(sa);
 }
 
 static void
-clear_socket_set(socket_set *sa)
+add_socket_to_set(socket_set *sa, CState *st)
 {
-	sa->curfds = 0;
-}
+	int			fd = PQsocket(st->con);
 
-static void
-add_socket_to_set(socket_set *sa, int fd, int idx)
-{
-	Assert(idx < sa->maxfds && idx == sa->curfds);
-	sa->pollfds[idx].fd = fd;
-	sa->pollfds[idx].events = POLLIN;
-	sa->pollfds[idx].revents = 0;
+	/*
+	 * Adding a client that is already in the set (sockidx >= 0) is a no-op,
+	 * so callers can invoke it unconditionally.
+	 */
+	if (st->sockidx >= 0)
+	{
+		Assert(st->sockidx < sa->curfds &&
+			   sa->pollfds[st->sockidx].events == POLLIN);
+		return;
+	}
+
+	Assert(sa->curfds < sa->maxfds);
+	sa->pollfds[sa->curfds].fd = fd;
+	sa->pollfds[sa->curfds].events = POLLIN;
+	sa->pollfds[sa->curfds].revents = 0;
+	sa->states[sa->curfds] = st;
+	st->sockidx = sa->curfds;
 	sa->curfds++;
 }
 
-static int
-wait_on_socket_set(socket_set *sa, int64 usecs)
+static void
+remove_socket_from_set(socket_set *sa, CState *st)
 {
+	int			idx = st->sockidx;
+
+	/*
+	 * Removing a client that is not in the set (sockidx == -1) is a no-op, so
+	 * callers can invoke it unconditionally.
+	 */
+	if (idx < 0)
+		return;
+
+	Assert(idx < sa->curfds);
+	st->sockidx = -1;
+
+	/* Compact the arrays by swapping with the last element */
+	if (idx != sa->curfds - 1)
+	{
+		sa->pollfds[idx] = sa->pollfds[sa->curfds - 1];
+		sa->states[idx] = sa->states[sa->curfds - 1];
+		sa->states[idx]->sockidx = idx;
+	}
+	sa->curfds--;
+}
+
+static int
+wait_on_socket_set(RunState *run, int64 usecs)
+{
+	socket_set *sa = run->sockets;
+	int			n;
+
+	if (sa->curfds == 0)
+		return 0;
+
 	if (usecs > 0)
 	{
 		struct timespec timeout;
 
 		timeout.tv_sec = usecs / 1000000;
 		timeout.tv_nsec = (usecs % 1000000) * 1000;
-		return ppoll(sa->pollfds, sa->curfds, &timeout, NULL);
+		n = ppoll(sa->pollfds, sa->curfds, &timeout, NULL);
 	}
 	else
 	{
-		return ppoll(sa->pollfds, sa->curfds, NULL, NULL);
+		n = ppoll(sa->pollfds, sa->curfds, NULL, NULL);
 	}
-}
 
-static bool
-socket_has_input(socket_set *sa, int fd, int idx)
-{
-	/*
-	 * In some cases, threadRun will apply clear_socket_set and then try to
-	 * apply socket_has_input anyway with arguments that it used before that,
-	 * or might've used before that except that it exited its setup loop
-	 * early.  Hence, if the socket set is empty, silently return false
-	 * regardless of the parameters.  If it's not empty, we can Assert that
-	 * the parameters match a previous call.
-	 */
-	if (sa->curfds == 0)
-		return false;
+	if (n == 0)
+		return 0;
 
-	Assert(idx < sa->curfds && sa->pollfds[idx].fd == fd);
-	return (sa->pollfds[idx].revents & POLLIN) != 0;
+	for (int i = 0; i < sa->curfds; i++)
+	{
+		if ((sa->pollfds[i].revents & POLLIN) != 0)
+		{
+			CState	   *st = sa->states[i];
+
+			if (st != NULL)
+				ready_add(run, st);
+		}
+	}
+
+	return n;
 }
 
 #endif							/* POLL_USING_PPOLL */
@@ -8052,25 +8181,38 @@ socket_has_input(socket_set *sa, int fd, int idx)
 static socket_set *
 alloc_socket_set(int count)
 {
-	return pg_malloc0_object(socket_set);
+	socket_set *sa;
+
+	sa = pg_malloc0_object(socket_set);
+	sa->curfds = 0;
+	sa->maxfd = -1;
+	sa->maxfds = count;
+	sa->states = pg_malloc0_array(CState *, count);
+	return sa;
 }
 
 static void
 free_socket_set(socket_set *sa)
 {
+	pg_free(sa->states);
 	pg_free(sa);
 }
 
 static void
-clear_socket_set(socket_set *sa)
+add_socket_to_set(socket_set *sa, CState *st)
 {
-	FD_ZERO(&sa->fds);
-	sa->maxfd = -1;
-}
+	int			fd = PQsocket(st->con);
+
+	/*
+	 * Adding a client that is already in the set (sockidx >= 0) is a no-op,
+	 * so callers can invoke it unconditionally.
+	 */
+	if (st->sockidx >= 0)
+	{
+		Assert(st->sockidx < sa->curfds && FD_ISSET(fd, &sa->fds));
+		return;
+	}
 
-static void
-add_socket_to_set(socket_set *sa, int fd, int idx)
-{
 	/* See connect_slot() for background on this code. */
 #ifdef WIN32
 	if (sa->fds.fd_count + 1 >= FD_SETSIZE)
@@ -8088,32 +8230,82 @@ add_socket_to_set(socket_set *sa, int fd, int idx)
 		exit(1);
 	}
 #endif
+
+	Assert(sa->curfds < sa->maxfds);
 	FD_SET(fd, &sa->fds);
 	if (fd > sa->maxfd)
 		sa->maxfd = fd;
+	sa->states[sa->curfds] = st;
+	st->sockidx = sa->curfds;
+	sa->curfds++;
+}
+
+static void
+remove_socket_from_set(socket_set *sa, CState *st)
+{
+	int			idx = st->sockidx;
+
+	/*
+	 * Removing a client that is not in the set (sockidx == -1) is a no-op, so
+	 * callers can invoke it unconditionally.
+	 */
+	if (idx < 0)
+		return;
+
+	Assert(idx < sa->curfds);
+	st->sockidx = -1;
+	FD_CLR(PQsocket(st->con), &sa->fds);
+
+	/* Compact the arrays by swapping with the last element */
+	if (idx != sa->curfds - 1)
+	{
+		sa->states[idx] = sa->states[sa->curfds - 1];
+		sa->states[idx]->sockidx = idx;
+	}
+	sa->curfds--;
 }
 
 static int
-wait_on_socket_set(socket_set *sa, int64 usecs)
+wait_on_socket_set(TState *thread, socket_set *sa, int64 usecs)
 {
+	int			n;
+	fd_set		rfds;
+
+	if (sa->curfds == 0)
+		return 0;
+
+	/*
+	 * select() destructively modifies its input set, clearing bits for
+	 * sockets that are not ready.  So we pass a copy of our registration set
+	 * (sa->fds) as the input, and store the result in sa->rfds.
+	 */
+	memcpy(&rfds, &sa->fds, sizeof(fd_set));
 	if (usecs > 0)
 	{
 		struct timeval timeout;
 
 		timeout.tv_sec = usecs / 1000000;
 		timeout.tv_usec = usecs % 1000000;
-		return select(sa->maxfd + 1, &sa->fds, NULL, NULL, &timeout);
+
+		n = select(sa->maxfd + 1, &rfds, NULL, NULL, &timeout);
 	}
 	else
 	{
-		return select(sa->maxfd + 1, &sa->fds, NULL, NULL, NULL);
+		n = select(sa->maxfd + 1, &rfds, NULL, NULL, NULL);
 	}
-}
 
-static bool
-socket_has_input(socket_set *sa, int fd, int idx)
-{
-	return (FD_ISSET(fd, &sa->fds) != 0);
+	if (n == 0)
+		return 0;
+
+	for (int i = 0; i < sa->curfds; i++)
+	{
+		CState	   *st = sa->states[i];
+
+		if (FD_ISSET(PQsocket(st->con), &rfds) != 0)
+			ready_add(thread, st);
+	}
+
+	return n;
 }
 
 #endif							/* POLL_USING_SELECT */
diff --git a/src/common/meson.build b/src/common/meson.build
index fc89a173346..917e1111ce2 100644
--- a/src/common/meson.build
+++ b/src/common/meson.build
@@ -20,6 +20,7 @@ common_sources = files(
   'kwlookup.c',
   'link-canary.c',
   'md5_common.c',
+  'pairingheap.c',
   'parse_manifest.c',
   'percentrepl.c',
   'pg_get_line.c',
diff --git a/src/backend/lib/pairingheap.c b/src/common/pairingheap.c
similarity index 98%
rename from src/backend/lib/pairingheap.c
rename to src/common/pairingheap.c
index 9bb3dd68140..6965c43279a 100644
--- a/src/backend/lib/pairingheap.c
+++ b/src/common/pairingheap.c
@@ -17,12 +17,16 @@
  * Portions Copyright (c) 2012-2026, PostgreSQL Global Development Group
  *
  * IDENTIFICATION
- *	  src/backend/lib/pairingheap.c
+ *	  src/common/pairingheap.c
  *
  *-------------------------------------------------------------------------
  */
 
+#ifdef FRONTEND
+#include "postgres_fe.h"
+#else
 #include "postgres.h"
+#endif
 
 #include "lib/pairingheap.h"
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 278b2f3194b..75f07706a79 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2720,6 +2720,7 @@ RuleInfo
 RuleLock
 RuleStmt
 RunMode
+RunState
 RunningTransactions
 RunningTransactionsData
 SASLStatus
-- 
2.43.0

