From c0961a66c268e7623a1fe3a2ff7ed8f228bdddaf Mon Sep 17 00:00:00 2001
From: Yura Sokolov <y.sokolov@postgrespro.ru>
Date: Sun, 6 Dec 2026 17:46:01 +0300
Subject: [PATCH v1 8/8] pgbench: add a low-latency mode

By default a thread picks up client responses only while blocked in
wait_on_socket_set(), that is, when the ready list is empty and no sleep
or throttle timer has expired yet.  While it is busy running the ready
clients, responses arriving meanwhile stay unread until the next
blocking wait.

In low-latency mode, enabled with --low-latency or
PGBENCH_LOW_LATENCY, the thread also checks the sockets whenever it
would otherwise go on without waiting: with a zero timeout it merges
the clients whose responses have arrived into the ready list in the
same pass, instead of leaving them to the next blocking wait.

For these frequent checks to stay cheap, in low-latency mode the socket
is taken out of the set when the client's transaction ends, and put
back when the next command starts; CORO_SLEEP_TILL already did so for the
batch wait backends.  The batch backends (ppoll and select) hand their
whole registration set to the kernel on every wait, so keeping the set
to the clients actually waiting for data pays off, and removing an idle
socket is plain array bookkeeping.  epoll keeps registrations in the
kernel and returns only ready sockets, so leaving them in place costs
nothing there, while removing would add epoll_ctl() calls.

wait_on_socket_set() gets a timeout convention that can say "don't
block": PG_INT64_MAX waits forever (the connection-establishment loop
previously spelled an endless wait with a zero timeout), any other
value is a timeout in microseconds, and when no sockets are registered
the function sleeps the timeout out instead of returning immediately,
which would have spun the thread.
---
 doc/src/sgml/ref/pgbench.sgml | 23 +++++++++++
 src/bin/pgbench/pgbench.c     | 76 +++++++++++++++++++++++++----------
 2 files changed, 78 insertions(+), 21 deletions(-)

diff --git a/doc/src/sgml/ref/pgbench.sgml b/doc/src/sgml/ref/pgbench.sgml
index f7e044f82ff..ceb74bd0492 100644
--- a/doc/src/sgml/ref/pgbench.sgml
+++ b/doc/src/sgml/ref/pgbench.sgml
@@ -835,6 +835,19 @@ pgbench <optional> <replaceable>options</replaceable> </optional> <replaceable>d
       </listitem>
      </varlistentry>
 
+     <varlistentry id="pgbench-option-low-latency">
+      <term><option>--low-latency</option></term>
+      <listitem>
+       <para>
+        Run in low-latency mode: <application>pgbench</application> threads
+        check client sockets on every pass of the event loop, so a response
+        that arrived while the thread was busy with other clients is
+        dispatched immediately, rather than waiting for the next blocking
+        check.  This can slightly increase CPU usage.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="pgbench-option-max-tries">
       <term><option>--max-tries=<replaceable>number_of_tries</replaceable></option></term>
       <listitem>
@@ -1066,6 +1079,16 @@ pgbench <optional> <replaceable>options</replaceable> </optional> <replaceable>d
     </listitem>
    </varlistentry>
 
+   <varlistentry id="pgbench-environment-pgbenchlowlatency">
+    <term><envar>PGBENCH_LOW_LATENCY</envar></term>
+    <listitem>
+     <para>
+      Behaves the same as the <option>--low-latency</option> option.  The
+      option takes precedence over the environment variable.
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry id="pgbench-environment-pgbenchsocketwait">
     <term><envar>PGBENCH_SOCKET_WAIT</envar></term>
     <listitem>
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 36df8aafca8..f2ba89e7907 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -337,6 +337,7 @@ static bool is_connect;			/* establish connection for each transaction */
 static bool report_per_command = false; /* report per-command latencies,
 										 * retries after errors and failures
 										 * (errors without retrying) */
+static bool low_latency = false;	/* low latency mode by polling fds often */
 static int	main_pid;			/* main process id used in log filename */
 
 /*
@@ -998,6 +999,7 @@ usage(void)
 		   "  --failures-detailed      report the failures grouped by basic types\n"
 		   "  --log-prefix=PREFIX      prefix for transaction time log file\n"
 		   "                           (default: \"pgbench_log\")\n"
+		   "  --low-latency            enable low latency mode by checking sockets more often\n"
 		   "  --max-tries=NUM          max number of tries to run transaction (default: 1)\n"
 		   "  --progress-timestamp     use Unix epoch timestamps for progress\n"
 		   "  --random-seed=SEED       set random seed (\"time\", \"rand\", integer)\n"
@@ -4080,7 +4082,17 @@ l_end_tx:
 		run->thread->conn_duration += run->now - start;
 	}
 
-	/* next transaction (script) */
+	/*
+	 * Next transaction (script).  In low-latency mode the sockets are checked
+	 * on every loop iteration, so for the batch wait backends (ppoll and
+	 * select), which hand their whole registration set to the kernel on every
+	 * wait, keep the client's socket out of the set while it is not waiting
+	 * for data; add_socket_to_set() puts it back when the next command
+	 * starts.  (epoll keeps registrations in the kernel and returns only
+	 * ready sockets, so they are left as is there.)
+	 */
+	if (low_latency && run->sockets->batch)
+		remove_socket_from_set(run->sockets, st);
 	CORO_SCHED();
 	goto l_restart;
 
@@ -7098,6 +7110,7 @@ main(int argc, char **argv)
 		{"debug", no_argument, NULL, 17},
 		{"continue-on-error", no_argument, NULL, 18},
 		{"socket-wait", required_argument, NULL, 19},
+		{"low-latency", no_argument, NULL, 256},
 		{NULL, 0, NULL, 0}
 	};
 
@@ -7462,6 +7475,10 @@ main(int argc, char **argv)
 				benchmarking_option_set = true;
 				socket_wait_opt = pg_strdup(optarg);
 				break;
+			case 256:			/* low-latency */
+				benchmarking_option_set = true;
+				low_latency = true;
+				break;
 			default:
 				/* getopt_long already emitted a complaint */
 				pg_log_error_hint("Try \"%s --help\" for more information.", progname);
@@ -7469,6 +7486,18 @@ main(int argc, char **argv)
 		}
 	}
 
+	/* PGBENCH_LOW_LATENCY turns on the mode, like the --low-latency option */
+	{
+		char	   *low_lat = getenv("PGBENCH_LOW_LATENCY");
+
+		if (low_lat && low_lat[0] &&
+			(atoi(low_lat) || strchr("tTyY", low_lat[0])))
+		{
+			benchmarking_option_set = true;
+			low_latency = true;
+		}
+	}
+
 	/* set default script if none */
 	if (num_scripts == 0 && !is_init_mode)
 	{
@@ -7939,7 +7968,7 @@ threadRun(void *arg)
 
 			if (run.sockets->curfds > 0)
 			{
-				int			rc = wait_on_socket_set(&run, 0);
+				int			rc = wait_on_socket_set(&run, PG_INT64_MAX);
 
 				if (rc < 0)
 				{
@@ -8021,7 +8050,8 @@ threadRun(void *arg)
 		 * to consider sleep/throttle timers here.
 		 *
 		 * If any client is ready to run (in the ready list), we must not
-		 * wait.
+		 * sleep; in low-latency mode the wait below still peeks at the
+		 * sockets.
 		 */
 		if (run.ready != NULL)
 			min_usec = 0;
@@ -8046,27 +8076,24 @@ threadRun(void *arg)
 		}
 
 		/*
-		 * If no clients are ready to execute actions, sleep until we receive
-		 * data on some client socket or the timeout (if any) elapses.
+		 * If there is nothing to run yet, wait until we receive data on some
+		 * client socket or the timeout (if any) elapses.  In low-latency mode,
+		 * also check the sockets without blocking whenever any are
+		 * registered, so responses that arrived while we were busy with other
+		 * clients are picked up now instead of after the next blocking wait.
 		 */
-		if (min_usec > 0)
+		if (min_usec > 0 ||
+			(low_latency && run.sockets->curfds > 0))
 		{
 			int			rc = 0;
 
-			if (min_usec != PG_INT64_MAX)
+			if (run.sockets->curfds > 0)
 			{
-				if (run.sockets->curfds > 0)
-				{
-					rc = wait_on_socket_set(&run, min_usec);
-				}
-				else			/* nothing active, simple sleep */
-				{
-					pg_usleep(min_usec);
-				}
+				rc = wait_on_socket_set(&run, min_usec);
 			}
-			else				/* no explicit delay, wait without timeout */
+			else				/* nothing active, simple sleep */
 			{
-				rc = wait_on_socket_set(&run, 0);
+				pg_usleep(min_usec);
 			}
 
 			if (rc < 0)
@@ -8334,7 +8361,10 @@ setalarm(int seconds)
  *		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.
+ *		to expire.  The timeout is measured in microseconds; PG_INT64_MAX
+ *		waits forever, 0 just checks the sockets without blocking.  When no
+ *		sockets are registered, sleeps the timeout out instead, so an
+ *		infinite wait requires at least one registered socket.
  *		Returns result code of underlying syscall (>=0 if OK, else see errno).
  *		Calls ready_add for each socket that is ready.
  *
@@ -8655,14 +8685,18 @@ wait_on_socket_set(RunState *run, int64 usecs)
 	int			n;
 
 	if (sa->curfds == 0)
+	{
+		Assert(usecs != PG_INT64_MAX);
+		pg_usleep(usecs);
 		return 0;
+	}
 
 	if (sa->method == SOCKET_WAIT_EPOLL)
 	{
 #ifdef POLL_USING_EPOLL
 		struct epoll_event *events = sa->u.epoll.revents;
 
-		if (usecs > 0)
+		if (usecs != PG_INT64_MAX)
 		{
 			struct timespec timeout;
 
@@ -8694,7 +8728,7 @@ wait_on_socket_set(RunState *run, int64 usecs)
 	else if (sa->method == SOCKET_WAIT_PPOLL)
 	{
 #ifdef POLL_USING_PPOLL
-		if (usecs > 0)
+		if (usecs != PG_INT64_MAX)
 		{
 			struct timespec timeout;
 
@@ -8737,7 +8771,7 @@ wait_on_socket_set(RunState *run, int64 usecs)
 		 */
 		memcpy(&rfds, &sa->u.select.fds, sizeof(fd_set));
 		memcpy(&wfds, &sa->u.select.wfds, sizeof(fd_set));
-		if (usecs > 0)
+		if (usecs != PG_INT64_MAX)
 		{
 			struct timeval timeout;
 
-- 
2.43.0

