From a48901d6189f154feb9d53f9894a4fdcd91ae9c8 Mon Sep 17 00:00:00 2001
From: Yura Sokolov <y.sokolov@postgrespro.ru>
Date: Sun, 6 Dec 2026 17:27:47 +0300
Subject: [PATCH v1 6/8] pgbench: async query preparation

Prepared-mode queries are prepared with PQsendPrepare() in the
prepareCommandHandling()/preparePipelineHandling() coroutines, which
suspend in the socket set until the backend replies, so preparations
of other clients proceed in parallel instead of blocking.

\sleep, \startpipeline and \endpipeline, which may suspend, move from
executeMetaCommand() into a new metaCommandHandling() coroutine,
routed there by metaCommandAsync(); META_RESULT_SLEEP and
META_RESULT_WAIT_RESULT disappear.
---
 src/bin/pgbench/pgbench.c | 421 ++++++++++++++++++++++++--------------
 1 file changed, 272 insertions(+), 149 deletions(-)

diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 7470946c5b9..ccc609cf070 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -557,8 +557,6 @@ static THREAD_BARRIER_T barrier;
 typedef enum
 {
 	META_RESULT_END_COMMAND,
-	META_RESULT_SLEEP,
-	META_RESULT_WAIT_RESULT,
 	META_RESULT_ABORTED,
 } MetaCommandResult;
 
@@ -600,6 +598,7 @@ struct CState
 
 	int			use_file;		/* index in sql_script for this client */
 	int			command;		/* command number in script */
+	int			prepare_num;	/* number of the command being prepared */
 	int			num_syncs;		/* number of ongoing sync commands */
 	bool		received_sync;	/* last non-NULL result read by
 								 * discardUntilSync was a pipeline sync */
@@ -3109,72 +3108,12 @@ allocCStatePrepared(CState *st)
 	}
 }
 
-/*
- * Prepare the SQL command from st->use_file at command_num.
- */
-static void
-prepareCommand(CState *st, int command_num)
+static bool
+commandIsPrepared(CState *st)
 {
-	Command    *command = sql_script[st->use_file].commands[command_num];
-
-	/* No prepare for non-SQL commands */
-	if (command->type != SQL_COMMAND)
-		return;
-
 	if (!st->prepared)
-		allocCStatePrepared(st);
-
-	if (!st->prepared[st->use_file][command_num])
-	{
-		PGresult   *res;
-
-		pg_log_debug("client %d preparing %s", st->id, command->prepname);
-		res = PQprepare(st->con, command->prepname,
-						command->argv[0], command->argc - 1, NULL);
-		if (PQresultStatus(res) != PGRES_COMMAND_OK)
-			pg_log_error("%s", PQerrorMessage(st->con));
-		PQclear(res);
-		st->prepared[st->use_file][command_num] = true;
-	}
-}
-
-/*
- * Prepare all the commands in the script that come after the \startpipeline
- * that's at position st->command, and the first \endpipeline we find.
- *
- * This sets the ->prepared flag for each relevant command as well as the
- * \startpipeline itself, but doesn't move the st->command counter.
- */
-static void
-prepareCommandsInPipeline(CState *st)
-{
-	int			j;
-	Command   **commands = sql_script[st->use_file].commands;
-
-	Assert(commands[st->command]->type == META_COMMAND &&
-		   commands[st->command]->meta == META_STARTPIPELINE);
-
-	if (!st->prepared)
-		allocCStatePrepared(st);
-
-	/*
-	 * We set the 'prepared' flag on the \startpipeline itself to flag that we
-	 * don't need to do this next time without calling prepareCommand(), even
-	 * though we don't actually prepare this command.
-	 */
-	if (st->prepared[st->use_file][st->command])
-		return;
-
-	for (j = st->command + 1; commands[j] != NULL; j++)
-	{
-		if (commands[j]->type == META_COMMAND &&
-			commands[j]->meta == META_ENDPIPELINE)
-			break;
-
-		prepareCommand(st, j);
-	}
-
-	st->prepared[st->use_file][st->command] = true;
+		return false;
+	return st->prepared[st->use_file][st->command];
 }
 
 /* Send a SQL command, using the chosen querymode */
@@ -3209,9 +3148,9 @@ sendCommand(CState *st, Command *command)
 	{
 		const char *params[MAX_ARGS];
 
-		prepareCommand(st, st->command);
 		getQueryParams(&st->variables, command, params);
 
+		Assert(commandIsPrepared(st));
 		pg_log_debug("client %d sending %s", st->id, command->prepname);
 		r = PQsendQueryPrepared(st->con, command->prepname, command->argc - 1,
 								params, NULL, NULL, 0);
@@ -3764,6 +3703,10 @@ advanceConnectionState(RunState *run, CState *st)
 static CoroResult waitForResults(RunState *run, CState *st);
 static CoroResult waitForAbort(RunState *run, CState *st);
 static CoroResult discardUntilSync(RunState *run, CState *st);
+static CoroResult prepareCommandHandling(RunState *run, CState *st);
+static CoroResult preparePipelineHandling(RunState *run, CState *st);
+static CoroResult metaCommandHandling(RunState *run, CState *st);
+static bool metaCommandAsync(CState *st);
 
 /*
  * Run the transactions of one client: choose a script and execute its
@@ -3950,6 +3893,14 @@ l_start_command:
 			}
 		}
 
+		/* Wait until the command has been prepared, if needed */
+		if (querymode == QUERY_PREPARED && !commandIsPrepared(st))
+		{
+			st->prepare_num = st->command;
+			CORO_CALL(prepareCommandHandling);
+			command = sql_script[st->use_file].commands[st->command];
+		}
+
 		if (!sendCommand(st, command))
 		{
 			commandFailed(st, "SQL", "SQL command send failed");
@@ -3961,24 +3912,16 @@ l_start_command:
 	else if (command->type == META_COMMAND)
 	{
 		/*-----
-		 * Possible results when executing meta commands:
-		 * - on errors META_RESULT_ABORTED
-		 * - on sleep META_RESULT_SLEEP
-		 * - on \endpipeline META_RESULT_WAIT_RESULT
-		 * - else META_RESULT_END_COMMAND
+		 * \sleep, \startpipeline and \endpipeline may suspend, so they are
+		 * executed by metaCommandHandling(); other meta commands cannot.
 		 */
-		MetaCommandResult mres = executeMetaCommand(run, st);
-
-		if (mres == META_RESULT_ABORTED)
+		if (metaCommandAsync(st))
+			CORO_CALL(metaCommandHandling);
+		else if (executeMetaCommand(run, st) == META_RESULT_ABORTED)
 		{
 			st->estatus = ESTATUS_META_COMMAND_ERROR;
 			CORO_ABORT();
 		}
-		else if (mres == META_RESULT_SLEEP)
-			CORO_SLEEP_TILL(st->sleep_until);
-		else if (mres == META_RESULT_WAIT_RESULT)
-			CORO_CALL(waitForResults);
-		/* else	META_RESULT_END_COMMAND */
 	}
 
 	if (st->estatus != ESTATUS_NO_ERROR)
@@ -4315,6 +4258,252 @@ discardUntilSync(RunState *run, CState *st)
 	CORO_DISPATCH_END();
 }
 
+/*
+ * Coroutine preparing the SQL command of st->use_file at st->prepare_num:
+ * send PQsendPrepare() and suspend until the result arrives, then collect
+ * the results and record the command as prepared.
+ */
+static CoroResult
+prepareCommandHandling(RunState *run, CState *st)
+{
+	Command    *command = sql_script[st->use_file].commands[st->prepare_num];
+	PGresult   *res;
+
+	CORO_DISPATCH();
+
+	/* No prepare for non-SQL commands */
+	if (command->type != SQL_COMMAND)
+		CORO_RETURN();
+
+	if (!st->prepared)
+		allocCStatePrepared(st);
+
+	if (st->prepared[st->use_file][st->prepare_num])
+		CORO_RETURN();
+
+	pg_log_debug("client %d preparing %s", st->id, command->prepname);
+	if (!PQsendPrepare(st->con, command->prepname, command->argv[0],
+					   command->argc - 1, NULL))
+	{
+		commandFailed(st, "SQL", "sending prepare failed");
+		CORO_ABORT();
+	}
+
+	/*
+	 * Only check for new network data if we processed all data fetched prior.
+	 * Otherwise we end up doing a syscall for each individual pipelined
+	 * query, which has a measurable performance impact.
+	 */
+	while (PQisBusy(st->con))
+	{
+		if (!PQconsumeInput(st->con))
+		{
+			/* there's something wrong */
+			commandFailed(st, "Prepare", "perhaps the backend died while processing");
+			CORO_ABORT();
+		}
+		if (PQisBusy(st->con))
+		{
+			/* don't have the whole result yet */
+			add_socket_to_set(run->sockets, st);
+			CORO_WAIT();
+		}
+	}
+
+	while ((res = PQgetResult(st->con)) != NULL)
+	{
+		if (PQresultStatus(res) != PGRES_COMMAND_OK)
+			pg_log_error("%s", PQerrorMessage(st->con));
+		PQclear(res);
+	}
+
+	st->prepared[st->use_file][st->prepare_num] = true;
+
+	CORO_DISPATCH_END();
+}
+
+/*
+ * Coroutine preparing all the commands in the script that come after the
+ * \startpipeline that's at position st->command, until the first
+ * \endpipeline we find.
+ *
+ * This sets the ->prepared flag for each relevant command as well as the
+ * \startpipeline itself, but doesn't move the st->command counter.
+ */
+static CoroResult
+preparePipelineHandling(RunState *run, CState *st)
+{
+	Command   **commands = sql_script[st->use_file].commands;
+	Command    *command;
+
+	CORO_DISPATCH();
+
+	Assert(commands[st->command]->type == META_COMMAND &&
+		   commands[st->command]->meta == META_STARTPIPELINE);
+
+	if (!st->prepared)
+		allocCStatePrepared(st);
+
+	/*
+	 * We set the 'prepared' flag on the \startpipeline itself to flag that we
+	 * don't need to do this next time, even though we don't actually prepare
+	 * this command.
+	 */
+	if (st->prepared[st->use_file][st->command])
+		CORO_RETURN();
+
+	st->prepare_num = st->command;
+
+	for (;;)
+	{
+		st->prepare_num++;
+
+		command = commands[st->prepare_num];
+		if (command == NULL ||
+			(command->type == META_COMMAND &&
+			 command->meta == META_ENDPIPELINE))
+			break;
+
+		CORO_CALL(prepareCommandHandling);
+	}
+
+	st->prepared[st->use_file][st->command] = true;
+
+	CORO_DISPATCH_END();
+}
+
+/*
+ * Coroutine executing the "asynchronous" meta commands: \sleep, \startpipeline
+ * and \endpipeline. They are handled here rather than in executeMetaCommand()
+ * since they may suspend: \sleep waits in the wakeup heap, \startpipeline
+ * waits for the commands inside the pipeline to be prepared, and \endpipeline
+ * waits for the pipeline results.
+ */
+static CoroResult
+metaCommandHandling(RunState *run, CState *st)
+{
+	Command    *command = sql_script[st->use_file].commands[st->command];
+	int			argc;
+	char	  **argv;
+
+	CORO_DISPATCH();
+
+	Assert(command != NULL && command->type == META_COMMAND);
+
+	argc = command->argc;
+	argv = command->argv;
+
+	if (unlikely(__pg_log_level <= PG_LOG_DEBUG))
+	{
+		PQExpBufferData buf;
+
+		initPQExpBuffer(&buf);
+
+		printfPQExpBuffer(&buf, "client %d executing \\%s", st->id, argv[0]);
+		for (int i = 1; i < argc; i++)
+			appendPQExpBuffer(&buf, " %s", argv[i]);
+
+		pg_log_debug("%s", buf.data);
+
+		termPQExpBuffer(&buf);
+	}
+
+	if (command->meta == META_SLEEP)
+	{
+		int			usec;
+
+		/*
+		 * A \sleep doesn't execute anything, we just get the delay from the
+		 * argument, and wait in the wakeup heap.  (The per-command latency
+		 * will be recorded after the delay has elapsed.)
+		 */
+		if (!evaluateSleep(&st->variables, argc, argv, &usec))
+		{
+			commandFailed(st, "sleep", "execution of meta-command failed");
+			st->estatus = ESTATUS_META_COMMAND_ERROR;
+			CORO_ABORT();
+		}
+
+		st->sleep_until = pg_time_now_lazy(run) + usec;
+		CORO_SLEEP_TILL(st->sleep_until);
+	}
+	else if (command->meta == META_STARTPIPELINE)
+	{
+		/*
+		 * In pipeline mode, we use a workflow based on libpq pipeline
+		 * functions.
+		 */
+		if (querymode == QUERY_SIMPLE)
+		{
+			commandFailed(st, "startpipeline", "cannot use pipeline mode with the simple query protocol");
+			st->estatus = ESTATUS_META_COMMAND_ERROR;
+			CORO_ABORT();
+		}
+
+		/*
+		 * If we're in prepared-query mode, we need to prepare all the
+		 * commands that are inside the pipeline before we actually start the
+		 * pipeline itself.  This solves the problem that running BEGIN
+		 * ISOLATION LEVEL SERIALIZABLE in a pipeline would fail due to a
+		 * snapshot having been acquired by the prepare within the pipeline.
+		 * Preparation waits for the backend reply, so it is carried out
+		 * asynchronously by a coroutine.
+		 */
+		if (querymode == QUERY_PREPARED)
+			CORO_CALL(preparePipelineHandling);
+
+		if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
+		{
+			commandFailed(st, "startpipeline", "already in pipeline mode");
+			st->estatus = ESTATUS_META_COMMAND_ERROR;
+			CORO_ABORT();
+		}
+		if (PQenterPipelineMode(st->con) == 0)
+		{
+			commandFailed(st, "startpipeline", "failed to enter pipeline mode");
+			st->estatus = ESTATUS_META_COMMAND_ERROR;
+			CORO_ABORT();
+		}
+	}
+	else if (command->meta == META_ENDPIPELINE)
+	{
+		if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
+		{
+			commandFailed(st, "endpipeline", "not in pipeline mode");
+			st->estatus = ESTATUS_META_COMMAND_ERROR;
+			CORO_ABORT();
+		}
+		if (!PQpipelineSync(st->con))
+		{
+			commandFailed(st, "endpipeline", "failed to send a pipeline sync");
+			st->estatus = ESTATUS_META_COMMAND_ERROR;
+			CORO_ABORT();
+		}
+		st->num_syncs++;
+		/* Now wait for the PGRES_PIPELINE_SYNC and exit pipeline mode there */
+		/* collect pending results before getting out of pipeline mode */
+		CORO_CALL(waitForResults);
+	}
+	else
+		Assert(false);
+
+	CORO_DISPATCH_END();
+}
+
+/*
+ * Report whether the current meta command is executed asynchronously by
+ * metaCommandHandling() (as opposed to executeMetaCommand()).
+ */
+static bool
+metaCommandAsync(CState *st)
+{
+	Command    *command = sql_script[st->use_file].commands[st->command];
+
+	return command->meta == META_SLEEP ||
+		command->meta == META_STARTPIPELINE ||
+		command->meta == META_ENDPIPELINE;
+}
+
 /*
  * Execute the current meta command.  \sleep, \startpipeline and \endpipeline,
  * which may suspend, are handled by metaCommandHandling() instead.
@@ -4351,26 +4540,7 @@ executeMetaCommand(RunState *run, CState *st)
 		termPQExpBuffer(&buf);
 	}
 
-	if (command->meta == META_SLEEP)
-	{
-		int			usec;
-
-		/*
-		 * A \sleep doesn't execute anything, we just get the delay from the
-		 * argument, and enter the CSTATE_SLEEP state.  (The per-command
-		 * latency will be recorded in CSTATE_SLEEP state, not here, after the
-		 * delay has elapsed.)
-		 */
-		if (!evaluateSleep(&st->variables, argc, argv, &usec))
-		{
-			commandFailed(st, "sleep", "execution of meta-command failed");
-			return META_RESULT_ABORTED;
-		}
-
-		st->sleep_until = pg_time_now_lazy(run) + usec;
-		return META_RESULT_SLEEP;
-	}
-	else if (command->meta == META_SET)
+	if (command->meta == META_SET)
 	{
 		PgBenchExpr *expr = command->expr;
 		PgBenchValue result;
@@ -4464,39 +4634,7 @@ executeMetaCommand(RunState *run, CState *st)
 			commandFailed(st, "shell", "execution of meta-command failed");
 			return META_RESULT_ABORTED;
 		}
-	}
-	else if (command->meta == META_STARTPIPELINE)
-	{
-		/*
-		 * In pipeline mode, we use a workflow based on libpq pipeline
-		 * functions.
-		 */
-		if (querymode == QUERY_SIMPLE)
-		{
-			commandFailed(st, "startpipeline", "cannot use pipeline mode with the simple query protocol");
-			return META_RESULT_ABORTED;
-		}
 
-		/*
-		 * If we're in prepared-query mode, we need to prepare all the
-		 * commands that are inside the pipeline before we actually start the
-		 * pipeline itself.  This solves the problem that running BEGIN
-		 * ISOLATION LEVEL SERIALIZABLE in a pipeline would fail due to a
-		 * snapshot having been acquired by the prepare within the pipeline.
-		 */
-		if (querymode == QUERY_PREPARED)
-			prepareCommandsInPipeline(st);
-
-		if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
-		{
-			commandFailed(st, "startpipeline", "already in pipeline mode");
-			return META_RESULT_ABORTED;
-		}
-		if (PQenterPipelineMode(st->con) == 0)
-		{
-			commandFailed(st, "startpipeline", "failed to enter pipeline mode");
-			return META_RESULT_ABORTED;
-		}
 	}
 	else if (command->meta == META_SYNCPIPELINE)
 	{
@@ -4512,23 +4650,8 @@ executeMetaCommand(RunState *run, CState *st)
 		}
 		st->num_syncs++;
 	}
-	else if (command->meta == META_ENDPIPELINE)
-	{
-		if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
-		{
-			commandFailed(st, "endpipeline", "not in pipeline mode");
-			return META_RESULT_ABORTED;
-		}
-		if (!PQpipelineSync(st->con))
-		{
-			commandFailed(st, "endpipeline", "failed to send a pipeline sync");
-			return META_RESULT_ABORTED;
-		}
-		st->num_syncs++;
-		/* Now wait for the PGRES_PIPELINE_SYNC and exit pipeline mode there */
-		/* collect pending results before getting out of pipeline mode */
-		return META_RESULT_WAIT_RESULT;
-	}
+	else
+		Assert(false);
 
 	/*
 	 * executing the expression or shell command might have taken a
-- 
2.43.0

