From 9cae932f64fff6b81ed6718824a8cf479d3e3242 Mon Sep 17 00:00:00 2001
From: Yura Sokolov <y.sokolov@postgrespro.ru>
Date: Sun, 6 Dec 2026 17:31:37 +0300
Subject: [PATCH v1 7/8] pgbench: asynchronous connection

Add connectHandling(), a coroutine that establishes a connection with
PQconnectStartParams()/PQconnectPoll(), suspending in the socket set
while the socket is busy.  It cannot prompt for a password, as that
would block the thread; the connection made in main() is expected to
have prompted for it already.

Without -C, each thread establishes connections for its clients
before the start of the benchmark through the same event loop, so
several clients join concurrently: the number of connections per thread
being established at the same time is capped with
max(1, min(1000 / nthreads, 10)), so that the server is not flooded
with connection attempts it cannot accept fast enough.
---
 src/bin/pgbench/pgbench.c | 283 ++++++++++++++++++++++++++++++++------
 1 file changed, 240 insertions(+), 43 deletions(-)

diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index ccc609cf070..36df8aafca8 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -147,6 +147,9 @@ typedef struct socket_set
 	int			maxfds;			/* allocated length of states[] array */
 	int			curfds;			/* number currently in use */
 	CState	  **states;			/* maps slot index (0..curfds-1) to CState */
+	bool	   *read;			/* same length as states[]; whether the
+								 * registered socket waits for read or for
+								 * write */
 	socket_wait_method method;	/* wait backend, chosen at runtime */
 	bool		batch;			/* wait backend is batch based */
 
@@ -170,8 +173,11 @@ typedef struct socket_set
 #ifdef POLL_USING_SELECT
 		struct
 		{
-			int			maxfd;	/* largest FD currently set in fds */
-			fd_set		fds;	/* registration set: sockets we wait on */
+			int			maxfd;	/* largest FD currently set in the sets */
+			fd_set		fds;	/* registration set: sockets we wait to read
+								 * on */
+			fd_set		wfds;	/* registration set: sockets we wait to write
+								 * on */
 		}			select;
 #endif
 	}			u;
@@ -611,6 +617,7 @@ struct CState
 	pg_time_usec_t sleep_until; /* scheduled start time of next cmd */
 	pg_time_usec_t txn_begin;	/* used for measuring schedule lag times */
 	pg_time_usec_t stmt_begin;	/* used for measuring statement latencies */
+	pg_time_usec_t con_begin;	/* used for measuring connection time */
 
 	/* whether client prepared each command of each script */
 	bool	  **prepared;
@@ -866,6 +873,7 @@ static void setalarm(int seconds);
 static socket_set *alloc_socket_set(int count);
 static void free_socket_set(socket_set *sa);
 static void add_socket_to_set(socket_set *sa, CState *st);
+static void add_socket_to_wset(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 socket_wait_method choose_socket_wait_backend(int count);
@@ -1550,13 +1558,14 @@ tryExecuteStatement(PGconn *con, const char *sql)
 	PQclear(res);
 }
 
+static char *password = NULL;
+
 /* set up a connection to the backend */
 static PGconn *
 doConnect(void)
 {
 	PGconn	   *conn;
 	bool		new_pass;
-	static char *password = NULL;
 
 	/*
 	 * Start the connection.  Loop until we have a password if requested by
@@ -3708,6 +3717,96 @@ static CoroResult preparePipelineHandling(RunState *run, CState *st);
 static CoroResult metaCommandHandling(RunState *run, CState *st);
 static bool metaCommandAsync(CState *st);
 
+/*
+ * Establish a connection to the backend asynchronously.
+ *
+ * This is a coroutine: the connection is started with PQconnectStartParams()
+ * and polled with PQconnectPoll(), suspending in the socket set while the
+ * socket is busy, until it is established.
+ */
+static CoroResult
+connectHandling(RunState *run, CState *st)
+{
+	PostgresPollingStatusType pollres;
+
+	CORO_DISPATCH();
+
+	/*
+	 * Start the connection.  Unlike doConnect(), this does not prompt for a
+	 * password, as that would block the thread: if the backend requests a
+	 * password that was not supplied -- the connection pgbench makes in
+	 * main() should have prompted for it -- the attempt just fails.
+	 */
+	if (st->con == NULL)
+	{
+#define PARAMS_ARRAY_SIZE	7
+
+		const char *keywords[PARAMS_ARRAY_SIZE];
+		const char *values[PARAMS_ARRAY_SIZE];
+
+		keywords[0] = "host";
+		values[0] = pghost;
+		keywords[1] = "port";
+		values[1] = pgport;
+		keywords[2] = "user";
+		values[2] = username;
+		keywords[3] = "password";
+		values[3] = password;
+		keywords[4] = "dbname";
+		values[4] = dbName;
+		keywords[5] = "fallback_application_name";
+		values[5] = progname;
+		keywords[6] = NULL;
+		values[6] = NULL;
+
+		st->con = PQconnectStartParams(keywords, values, true);
+
+		if (!st->con)
+		{
+			pg_log_error("connection to database \"%s\" failed", dbName);
+			CORO_ABORT();
+		}
+	}
+
+	/*
+	 * Poll the connection until it is established, suspending in the socket
+	 * set while the socket is busy.  The wait direction asked by
+	 * PQconnectPoll() alternates, so the socket is registered in the
+	 * corresponding wait set on each suspension, and removed from the set
+	 * once the connection is established or failed.
+	 */
+	for (;;)
+	{
+		pollres = PQconnectPoll(st->con);
+
+		if (pollres == PGRES_POLLING_FAILED)
+		{
+			pg_log_error("client %d aborted while establishing connection: %s",
+						 st->id, PQerrorMessage(st->con));
+			PQfinish(st->con);
+			st->con = NULL;
+			CORO_ABORT();
+		}
+
+		if (pollres == PGRES_POLLING_OK)
+			CORO_RETURN();
+
+		/* the connection is still busy */
+		if (pollres == PGRES_POLLING_READING)
+			add_socket_to_set(run->sockets, st);
+		else if (pollres == PGRES_POLLING_WRITING)
+			add_socket_to_wset(run->sockets, st);
+		else
+			pg_fatal("client %d got unexpected connection state %d",
+					 st->id, PQstatus(st->con));
+
+		CORO_WAIT();
+		remove_socket_from_set(run->sockets, st);
+	}
+
+	CORO_DISPATCH_END();
+}
+
 /*
  * Run the transactions of one client: choose a script and execute its
  * commands.
@@ -3809,21 +3908,17 @@ l_recalc_throttle:
 	/* establish connection if needed, i.e. under --connect */
 	if (st->con == NULL)
 	{
-		pg_time_usec_t start = pg_time_now_lazy(run);
+		st->con_begin = pg_time_now_lazy(run);
 
-		if ((st->con = doConnect()) == NULL)
-		{
-			/*
-			 * as the bench is already running, we do not abort the process
-			 */
-			pg_log_error("client %d aborted while establishing connection", st->id);
-			CORO_ABORT();
-		}
+		/*
+		 * The connection is established asynchronously; on a failure only
+		 * this client is aborted, not the whole process, as the bench is
+		 * already running.
+		 */
+		CORO_CALL(connectHandling);
 
 		/* reset now after connection */
-		run->now = pg_time_now();
-
-		run->thread->conn_duration += run->now - start;
+		run->thread->conn_duration += pg_time_now_lazy(run) - st->con_begin;
 
 		/* Reset session-local state */
 		pg_free(st->prepared);
@@ -7791,17 +7886,9 @@ threadRun(void *arg)
 			pg_fatal("could not open logfile \"%s\": %m", logpath);
 	}
 
-	/*
-	 * Each client starts by executing its script; all clients are initially
-	 * ready.  Initialize the ready list and socket indexes as well.
-	 */
 	run.ready = NULL;
 	for (int i = 0; i < nstate; i++)
-	{
-		coro_invoke(&state[i], scriptHandling);
-		ready_add(&run, &state[i]);
 		state[i].sockidx = -1;
-	}
 
 	/* READY */
 	THREAD_BARRIER_WAIT(&barrier);
@@ -7815,18 +7902,96 @@ threadRun(void *arg)
 	/* STEADY */
 	if (!is_connect)
 	{
-		/* make connections to the database before starting */
-		for (int i = 0; i < nstate; i++)
+		/*
+		 * Make connections to the database before starting.  The connections
+		 * are established asynchronously, through the same event loop as the
+		 * benchmark itself, so clients of a thread connect in parallel:
+		 * connectHandling() does not block the thread.
+		 *
+		 * The number of connections being established at the same time is
+		 * limited: if too many clients start their connections at once, the
+		 * server cannot accept them fast enough and some of the attempts
+		 * fail.  A thread establishes at most max(1, min(1000 / nthreads,
+		 * 10)) connections simultaneously, so the total over the threads
+		 * stays within the order of 1000 while a small thread setup keeps a
+		 * wider parallelism per thread.
+		 */
+		int			max_connects = Max(1, Min(1000 / nthreads, 10));
+		int			nconnects = 0;	/* connections being established */
+		int			inext = 0;	/* next state to start connecting */
+
+		while (remains > 0)
 		{
-			if ((state[i].con = doConnect()) == NULL)
+			CState	   *ready;
+
+			/*
+			 * Start the connections of as many clients as the limit allows,
+			 * going on with the next ones as established connections free up
+			 * slots (nconnects-- below).
+			 */
+			for (; nconnects < max_connects && inext < nstate; inext++)
 			{
-				/* coldly abort on initial connection failure */
-				pg_fatal("could not create connection for client %d",
-						 state[i].id);
+				Assert(state[inext].con == NULL);
+				nconnects++;
+				coro_invoke(&state[inext], connectHandling);
+				ready_add(&run, &state[inext]);
+			}
+
+			if (run.sockets->curfds > 0)
+			{
+				int			rc = wait_on_socket_set(&run, 0);
+
+				if (rc < 0)
+				{
+					if (errno == EINTR)
+						continue;
+
+					/* must be something wrong */
+					pg_fatal("%s() failed: %m",
+							 socket_wait_backend_name(run.sockets->method));
+				}
+			}
+
+			ready = run.ready;
+			run.ready = NULL;
+
+			while (ready != NULL)
+			{
+				CState	   *next = ready->next_ready;
+				CoroResult	res;
+
+				ready->is_ready = false;
+
+				do
+					res = advanceConnectionState(&run, ready);
+				while (res == CORO_CONTINUE);
+
+				if (ready->aborted)
+				{
+					/* coldly abort on initial connection failure */
+					pg_fatal("could not create connection for client %d",
+							 ready->id);
+				}
+
+				if (res == CORO_DONE)
+				{
+					/* the connection is established */
+					nconnects--;
+					remains--;
+				}
+
+				ready = next;
 			}
 		}
 	}
 
+	remains = nstate;
+	for (int i = 0; i < nstate; i++)
+	{
+		coro_invoke(&state[i], scriptHandling);
+		ready_add(&run, &state[i]);
+	}
+
 	/* GO */
 	THREAD_BARRIER_WAIT(&barrier);
 
@@ -8265,6 +8430,7 @@ alloc_socket_set(int count)
 	sa->curfds = 0;
 	sa->method = method;
 	sa->states = pg_malloc0_array(CState *, count);
+	sa->read = (bool *) pg_malloc0(sizeof(bool) * count);
 
 	if (method == SOCKET_WAIT_EPOLL)
 	{
@@ -8318,11 +8484,12 @@ free_socket_set(socket_set *sa)
 	}
 
 	pg_free(sa->states);
+	pg_free(sa->read);
 	pg_free(sa);
 }
 
 static void
-add_socket_to_set(socket_set *sa, CState *st)
+add_socket_to_set_impl(socket_set *sa, CState *st, bool read)
 {
 	int			fd = PQsocket(st->con);
 
@@ -8334,11 +8501,16 @@ add_socket_to_set(socket_set *sa, CState *st)
 
 	/*
 	 * Adding a client that is already in the set (sockidx >= 0) is a no-op,
-	 * so callers can invoke it unconditionally.
+	 * so callers can invoke it unconditionally.  A client cannot be
+	 * registered for input and output at the same time; a registration switch
+	 * is done by removing the socket and adding it back in the other wait
+	 * set.
 	 */
 	if (st->sockidx >= 0)
 	{
-		Assert(st->sockidx < sa->curfds && sa->states[st->sockidx] == st);
+		Assert(st->sockidx < sa->curfds &&
+			   sa->states[st->sockidx] == st &&
+			   sa->read[st->sockidx] == read);
 		return;
 	}
 
@@ -8349,7 +8521,7 @@ add_socket_to_set(socket_set *sa, CState *st)
 #ifdef POLL_USING_EPOLL
 		struct epoll_event ev;
 
-		ev.events = EPOLLIN;
+		ev.events = read ? EPOLLIN : EPOLLOUT;
 		ev.data.ptr = st;
 		if (epoll_ctl(sa->u.epoll.epfd, EPOLL_CTL_ADD, fd, &ev) < 0)
 			pg_fatal("epoll_ctl(EPOLL_CTL_ADD) failed: %m");
@@ -8361,7 +8533,7 @@ add_socket_to_set(socket_set *sa, CState *st)
 	{
 #ifdef POLL_USING_PPOLL
 		sa->u.ppoll.pollfds[sa->curfds].fd = fd;
-		sa->u.ppoll.pollfds[sa->curfds].events = POLLIN;
+		sa->u.ppoll.pollfds[sa->curfds].events = read ? POLLIN : POLLOUT;
 		sa->u.ppoll.pollfds[sa->curfds].revents = 0;
 #else
 		pg_fatal("ppoll wait backend is not available in this build");
@@ -8387,7 +8559,10 @@ add_socket_to_set(socket_set *sa, CState *st)
 		}
 #endif
 
-		FD_SET(fd, &sa->u.select.fds);
+		if (read)
+			FD_SET(fd, &sa->u.select.fds);
+		else
+			FD_SET(fd, &sa->u.select.wfds);
 		if (fd > sa->u.select.maxfd)
 			sa->u.select.maxfd = fd;
 #else
@@ -8396,10 +8571,28 @@ add_socket_to_set(socket_set *sa, CState *st)
 	}
 
 	sa->states[sa->curfds] = st;
+	sa->read[sa->curfds] = read;
 	st->sockidx = sa->curfds;
 	sa->curfds++;
 }
 
+/*
+ * The two entry points, for sockets waiting for input and for output
+ * respectively.  Which set was chosen for a socket is remembered in
+ * sa->read[], so that a no-op re-add can be asserted.
+ */
+static void
+add_socket_to_set(socket_set *sa, CState *st)
+{
+	add_socket_to_set_impl(sa, st, true);
+}
+
+static void
+add_socket_to_wset(socket_set *sa, CState *st)
+{
+	add_socket_to_set_impl(sa, st, false);
+}
+
 static void
 remove_socket_from_set(socket_set *sa, CState *st)
 {
@@ -8439,6 +8632,7 @@ remove_socket_from_set(socket_set *sa, CState *st)
 	{
 #ifdef POLL_USING_SELECT
 		FD_CLR(PQsocket(st->con), &sa->u.select.fds);
+		FD_CLR(PQsocket(st->con), &sa->u.select.wfds);
 #else
 		pg_fatal("select wait backend is not available in this build");
 #endif
@@ -8447,6 +8641,7 @@ remove_socket_from_set(socket_set *sa, CState *st)
 	/* Compact the states array by swapping with the last element */
 	if (idx != sa->curfds - 1)
 	{
+		sa->read[idx] = sa->read[sa->curfds - 1];
 		sa->states[idx] = sa->states[sa->curfds - 1];
 		sa->states[idx]->sockidx = idx;
 	}
@@ -8517,7 +8712,7 @@ wait_on_socket_set(RunState *run, int64 usecs)
 
 		for (int i = 0; i < sa->curfds; i++)
 		{
-			if ((sa->u.ppoll.pollfds[i].revents & POLLIN) != 0)
+			if ((sa->u.ppoll.pollfds[i].revents & (POLLIN | POLLOUT)) != 0)
 			{
 				CState	   *st = (CState *) sa->states[i];
 
@@ -8533,14 +8728,15 @@ wait_on_socket_set(RunState *run, int64 usecs)
 	{
 #ifdef POLL_USING_SELECT
 		fd_set		rfds;
+		fd_set		wfds;
 
 		/*
-		 * select() destructively modifies its input set, clearing bits for
-		 * sockets that are not ready.  So we pass a copy of our registration
-		 * set (sa->u.select.fds) as the input, and store the result in
-		 * sa->u.select.rfds.
+		 * select() destructively modifies its input sets, clearing bits for
+		 * sockets that are not ready.  So we pass copies of our registration
+		 * sets as the input.
 		 */
 		memcpy(&rfds, &sa->u.select.fds, sizeof(fd_set));
+		memcpy(&wfds, &sa->u.select.wfds, sizeof(fd_set));
 		if (usecs > 0)
 		{
 			struct timeval timeout;
@@ -8548,12 +8744,12 @@ wait_on_socket_set(RunState *run, int64 usecs)
 			timeout.tv_sec = usecs / 1000000;
 			timeout.tv_usec = usecs % 1000000;
 
-			n = select(sa->u.select.maxfd + 1, &rfds, NULL, NULL,
+			n = select(sa->u.select.maxfd + 1, &rfds, &wfds, NULL,
 					   &timeout);
 		}
 		else
 		{
-			n = select(sa->u.select.maxfd + 1, &rfds, NULL, NULL,
+			n = select(sa->u.select.maxfd + 1, &rfds, &wfds, NULL,
 					   NULL);
 		}
 
@@ -8563,8 +8759,9 @@ wait_on_socket_set(RunState *run, int64 usecs)
 		for (int i = 0; i < sa->curfds; i++)
 		{
 			CState	   *st = sa->states[i];
+			int			fd = PQsocket(st->con);
 
-			if (FD_ISSET(PQsocket(st->con), &rfds) != 0)
+			if (FD_ISSET(fd, &rfds) || FD_ISSET(fd, &wfds))
 				ready_add(run, st);
 		}
 #else
-- 
2.43.0

