From 70c747f7d6ab49917b00920b06d08cbc7c6c1503 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 5/8] pgbench: replace the connection state machine with a
 stackless coroutine

Turn advanceConnectionState() into a resumable coroutine: each CState
carries a small stack of Coroutine frames, each remembering the
function and the line to resume at.  CORO_WAIT and friends save the
resume point (__LINE__) and return CORO_YIELD to the scheduler, which
goes on to advance other clients; a later CORO_DISPATCH() switches on
the saved line.  scriptHandling, waitForResults, waitForAbort and
discardUntilSync become plain nested functions instead of interleaved
states of one state machine.

The ConnectionStateEnum and its per-state cases are gone; the change
is otherwise mechanical, with no change in behavior.
---
 src/bin/pgbench/pgbench.c        | 1556 ++++++++++++++----------------
 src/tools/pgindent/typedefs.list |    3 +
 2 files changed, 729 insertions(+), 830 deletions(-)

diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index e6db543a814..7470946c5b9 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -126,6 +126,7 @@
  */
 
 typedef struct CState CState;
+typedef struct RunState RunState;
 
 typedef enum
 {
@@ -550,117 +551,6 @@ static pg_prng_state base_random_sequence;
 /* Synchronization barrier for start and connection */
 static THREAD_BARRIER_T barrier;
 
-/*
- * Connection state machine states.
- */
-typedef enum
-{
-	/*
-	 * The client must first choose a script to execute.  Once chosen, it can
-	 * either be throttled (state CSTATE_PREPARE_THROTTLE under --rate), start
-	 * right away (state CSTATE_START_TX) or not start at all if the timer was
-	 * exceeded (state CSTATE_FINISHED).
-	 */
-	CSTATE_CHOOSE_SCRIPT,
-
-	/*
-	 * CSTATE_START_TX performs start-of-transaction processing.  Establishes
-	 * a new connection for the transaction in --connect mode, records the
-	 * transaction start time, and proceed to the first command.
-	 *
-	 * Note: once a script is started, it will either error or run till its
-	 * end, where it may be interrupted. It is not interrupted while running,
-	 * so pgbench --time is to be understood as tx are allowed to start in
-	 * that time, and will finish when their work is completed.
-	 */
-	CSTATE_START_TX,
-
-	/*
-	 * In CSTATE_PREPARE_THROTTLE state, we calculate when to begin the next
-	 * transaction, and advance to CSTATE_THROTTLE.  CSTATE_THROTTLE state
-	 * sleeps until that moment, then advances to CSTATE_START_TX, or
-	 * CSTATE_FINISHED if the next transaction would start beyond the end of
-	 * the run.
-	 */
-	CSTATE_PREPARE_THROTTLE,
-	CSTATE_THROTTLE,
-
-	/*
-	 * We loop through these states, to process each command in the script:
-	 *
-	 * CSTATE_START_COMMAND starts the execution of a command.  On a SQL
-	 * command, the command is sent to the server, and we move to
-	 * CSTATE_WAIT_RESULT state unless in pipeline mode. On a \sleep
-	 * meta-command, the timer is set, and we enter the CSTATE_SLEEP state to
-	 * wait for it to expire. Other meta-commands are executed immediately. If
-	 * the command about to start is actually beyond the end of the script,
-	 * advance to CSTATE_END_TX.
-	 *
-	 * CSTATE_WAIT_RESULT waits until we get a result set back from the server
-	 * for the current command.
-	 *
-	 * CSTATE_SLEEP waits until the end of \sleep.
-	 *
-	 * CSTATE_END_COMMAND records the end-of-command timestamp, increments the
-	 * command counter, and loops back to CSTATE_START_COMMAND state.
-	 *
-	 * CSTATE_SKIP_COMMAND is used by conditional branches which are not
-	 * executed. It quickly skip commands that do not need any evaluation.
-	 * This state can move forward several commands, till there is something
-	 * to do or the end of the script.
-	 */
-	CSTATE_START_COMMAND,
-	CSTATE_WAIT_RESULT,
-	CSTATE_SLEEP,
-	CSTATE_END_COMMAND,
-	CSTATE_SKIP_COMMAND,
-
-	/*
-	 * States for failed commands.
-	 *
-	 * If the SQL/meta command fails, in CSTATE_ERROR clean up after an error:
-	 * (1) clear the conditional stack; (2) if we have an unterminated
-	 * (possibly failed) transaction block, send the rollback command to the
-	 * server and wait for the result in CSTATE_WAIT_ROLLBACK_RESULT.  If
-	 * something goes wrong with rolling back, go to CSTATE_ABORTED.
-	 *
-	 * But if everything is ok we are ready for future transactions: if this
-	 * is a serialization or deadlock error and we can re-execute the
-	 * transaction from the very beginning, go to CSTATE_RETRY; otherwise go
-	 * to CSTATE_FAILURE.
-	 *
-	 * In CSTATE_RETRY report an error, set the same parameters for the
-	 * transaction execution as in the previous tries and process the first
-	 * transaction command in CSTATE_START_COMMAND.
-	 *
-	 * In CSTATE_FAILURE report a failure, set the parameters for the
-	 * transaction execution as they were before the first run of this
-	 * transaction (except for a random state) and go to CSTATE_END_TX to
-	 * complete this transaction.
-	 */
-	CSTATE_ERROR,
-	CSTATE_WAIT_ROLLBACK_RESULT,
-	CSTATE_RETRY,
-	CSTATE_FAILURE,
-
-	/*
-	 * CSTATE_END_TX performs end-of-transaction processing.  It calculates
-	 * latency, and logs the transaction.  In --connect mode, it closes the
-	 * current connection.
-	 *
-	 * Then either starts over in CSTATE_CHOOSE_SCRIPT, or enters
-	 * CSTATE_FINISHED if we have no more work to do.
-	 */
-	CSTATE_END_TX,
-
-	/*
-	 * Final states.  CSTATE_ABORTED means that the script execution was
-	 * aborted because a command failed, CSTATE_FINISHED means success.
-	 */
-	CSTATE_ABORTED,
-	CSTATE_FINISHED,
-} ConnectionStateEnum;
-
 /*
  * Result of executeMetaCommand().
  */
@@ -672,6 +562,22 @@ typedef enum
 	META_RESULT_ABORTED,
 } MetaCommandResult;
 
+typedef enum
+{
+	CORO_DONE,
+	CORO_CONTINUE,
+	CORO_YIELD,
+} CoroResult;
+
+typedef CoroResult (*CoroFunc) (RunState *run, CState *st);
+
+typedef struct
+{
+	CoroFunc	func;
+	int			line;
+} Coroutine;
+#define CORO_STACK 4
+
 /*
  * Connection state.
  */
@@ -679,9 +585,13 @@ struct CState
 {
 	PGconn	   *con;			/* connection handle to DB */
 	int			id;				/* client No. */
-	ConnectionStateEnum state;	/* state machine's current state. */
 	ConditionalStack cstack;	/* enclosing conditionals state */
 
+	bool		finished;
+	bool		aborted;
+	uint16		coro_depth;
+	Coroutine	coro_stack[CORO_STACK];
+
 	/*
 	 * Separate randomness for each client. This is used for random functions
 	 * PGBENCH_RANDOM_* during the execution of the script.
@@ -691,6 +601,8 @@ struct CState
 	int			use_file;		/* index in sql_script for this client */
 	int			command;		/* command number in script */
 	int			num_syncs;		/* number of ongoing sync commands */
+	bool		received_sync;	/* last non-NULL result read by
+								 * discardUntilSync was a pipeline sync */
 
 	/* client variables */
 	Variables	variables;
@@ -3647,75 +3559,6 @@ doRetry(RunState *run, CState *st)
 	return true;
 }
 
-/*
- * Read and discard results until the last sync point.
- */
-static int
-discardUntilSync(CState *st)
-{
-	bool		received_sync = false;
-
-	/*
-	 * Send a Sync message to ensure at least one PGRES_PIPELINE_SYNC is
-	 * received and to avoid an infinite loop, since all earlier ones may have
-	 * already been received.
-	 */
-	if (!PQpipelineSync(st->con))
-	{
-		pg_log_error("client %d aborted: failed to send a pipeline sync",
-					 st->id);
-		return 0;
-	}
-
-	/*
-	 * Continue reading results until the last sync point, i.e., until
-	 * reaching null just after PGRES_PIPELINE_SYNC.
-	 */
-	for (;;)
-	{
-		PGresult   *res = PQgetResult(st->con);
-
-		if (PQstatus(st->con) == CONNECTION_BAD)
-		{
-			pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
-						 st->id);
-			PQclear(res);
-			return 0;
-		}
-
-		if (PQresultStatus(res) == PGRES_PIPELINE_SYNC)
-			received_sync = true;
-		else if (received_sync && res == NULL)
-		{
-			/*
-			 * Reset ongoing sync count to 0 since all PGRES_PIPELINE_SYNC
-			 * results have been discarded.
-			 */
-			st->num_syncs = 0;
-			break;
-		}
-		else
-		{
-			/*
-			 * If a PGRES_PIPELINE_SYNC is followed by something other than
-			 * PGRES_PIPELINE_SYNC or NULL, another PGRES_PIPELINE_SYNC will
-			 * appear later. Reset received_sync to false to wait for it.
-			 */
-			received_sync = false;
-		}
-		PQclear(res);
-	}
-
-	/* exit pipeline */
-	if (PQexitPipelineMode(st->con) != 1)
-	{
-		pg_log_error("client %d aborted: failed to exit pipeline mode for rolling back the failed transaction",
-					 st->id);
-		return 0;
-	}
-	return 1;
-}
-
 /*
  * Get the transaction status at the end of a command especially for
  * checking if we are in a (failed) transaction block.
@@ -3791,15 +3634,6 @@ printVerboseErrorMessages(RunState *run, CState *st, 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.
@@ -3815,623 +3649,677 @@ ready_add(RunState *run, CState *st)
 	run->ready = st;
 }
 
-/*
- * Advance the state machine of a connection.
- */
-static void
+static CoroResult coro_invoke(CState *st, CoroFunc func);
+static CoroResult coro_abort(CState *st);
+static CoroResult coro_return(CState *st);
+
+static CoroResult
+coro_invoke(CState *st, CoroFunc func)
+{
+	if (st->coro_depth >= CORO_STACK)
+	{
+		pg_log_error("Coroutine stack overflow");
+		return coro_abort(st);
+	}
+	Assert(!st->aborted);
+	st->coro_stack[st->coro_depth].func = func;
+	st->coro_stack[st->coro_depth].line = 0;
+	st->coro_depth++;
+	return CORO_CONTINUE;
+}
+
+static CoroResult
+coro_abort(CState *st)
+{
+	st->aborted = true;
+	st->coro_depth = 0;
+	return CORO_DONE;
+}
+
+static CoroResult
+coro_return(CState *st)
+{
+	if (st->coro_depth == 0)
+	{
+		pg_log_error("Coroutine stack exhausted");
+		return coro_abort(st);
+	}
+	Assert(!st->aborted);
+	st->coro_depth--;
+	if (st->coro_depth > 0)
+		return CORO_CONTINUE;
+	return CORO_DONE;
+}
+
+static CoroResult
 advanceConnectionState(RunState *run, CState *st)
 {
-	/*
-	 * Loop in the state machine, until we have to wait for a result from the
-	 * server or have to sleep for throttling or \sleep.
-	 *
-	 * Note: In the switch-statement below, 'break' will loop back here,
-	 * meaning "continue in the state machine".  Return is used to return to
-	 * the caller, giving the thread the opportunity to advance another
-	 * client.
-	 */
-	for (;;)
-	{
-		Command    *command;
-
-		switch (st->state)
-		{
-				/* Select transaction (script) to run.  */
-			case CSTATE_CHOOSE_SCRIPT:
-				st->use_file = chooseScript(run->thread);
-				Assert(conditional_stack_empty(st->cstack));
-
-				/* reset transaction variables to default values */
-				st->estatus = ESTATUS_NO_ERROR;
-				st->tries = 1;
-
-				pg_log_debug("client %d executing script \"%s\"",
-							 st->id, sql_script[st->use_file].desc);
-
-				/*
-				 * If time is over, we're done; otherwise, get ready to start
-				 * a new transaction, or to get throttled if that's requested.
-				 */
-				st->state = timer_exceeded ? CSTATE_FINISHED :
-					throttle_delay > 0 ? CSTATE_PREPARE_THROTTLE : CSTATE_START_TX;
-				break;
-
-				/* Start new transaction (script) */
-			case CSTATE_START_TX:
-				/* establish connection if needed, i.e. under --connect */
-				if (st->con == NULL)
-				{
-					pg_time_usec_t start = 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);
-						st->state = CSTATE_ABORTED;
-						break;
-					}
-
-					/* reset now after connection */
-					run->now = pg_time_now();
-
-					run->thread->conn_duration += run->now - start;
-
-					/* Reset session-local state */
-					pg_free(st->prepared);
-					st->prepared = NULL;
-				}
-
-				/*
-				 * It is the first try to run this transaction. Remember the
-				 * random state: maybe it will get an error and we will need
-				 * to run it again.
-				 */
-				st->random_state = st->cs_func_rs;
-
-				/* record transaction start time */
-				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 = run->now;
-
-				/* Begin with the first command */
-				st->state = CSTATE_START_COMMAND;
-				st->command = 0;
-				break;
-
-				/*
-				 * Handle throttling once per transaction by sleeping.
-				 */
-			case CSTATE_PREPARE_THROTTLE:
-
-				/*
-				 * Generate a delay such that the series of delays will
-				 * approximate a Poisson distribution centered on the
-				 * throttle_delay time.
-				 *
-				 * If transactions are too slow or a given wait is shorter
-				 * than a transaction, the next transaction will start right
-				 * away.
-				 */
-				Assert(throttle_delay > 0);
-
-				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
-				 * so that the transaction will miss the latency limit even if
-				 * it completed immediately, skip this time slot and loop to
-				 * reschedule.
-				 */
-				if (latency_limit)
-				{
-					if (run->thread->throttle_trigger < pg_time_now_lazy(run) - latency_limit)
-					{
-						processXactStats(run, st, true);
-
-						/*
-						 * Finish client if -T or -t was exceeded.
-						 *
-						 * Stop counting skipped transactions under -T as soon
-						 * as the timer is exceeded. Because otherwise it can
-						 * take a very long time to count all of them
-						 * especially when quite a lot of them happen with
-						 * unrealistically high rate setting in -R, which
-						 * would prevent pgbench from ending immediately.
-						 * Because of this behavior, note that there is no
-						 * guarantee that all skipped transactions are counted
-						 * under -T though there is under -t. This is OK in
-						 * practice because it's very unlikely to happen with
-						 * realistic setting.
-						 */
-						if (timer_exceeded || (nxacts > 0 && st->cnt >= nxacts))
-							st->state = CSTATE_FINISHED;
-
-						/* Go back to top of loop with CSTATE_PREPARE_THROTTLE */
-						break;
-					}
-				}
-
-				/*
-				 * stop client if next transaction is beyond pgbench end of
-				 * execution; otherwise, throttle it.
-				 */
-				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);
-					if (run->sockets->batch)
-						remove_socket_from_set(run->sockets, st);
-					return;
-				}
-				break;
-
-				/*
-				 * Wait until it's time to start next transaction.
-				 */
-			case CSTATE_THROTTLE:
-				/* done sleeping, but don't start transaction if we're done */
-				st->state = timer_exceeded ? CSTATE_FINISHED : CSTATE_START_TX;
-				break;
-
-				/*
-				 * 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];
-
-				/*
-				 * Transition to script end processing if done, but close up
-				 * shop if a pipeline is open at this point.
-				 */
-				if (command == NULL)
-				{
-					if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
-						st->state = CSTATE_END_TX;
-					else
-					{
-						pg_log_error("client %d aborted: end of script reached with pipeline open",
-									 st->id);
-						st->state = CSTATE_ABORTED;
-					}
-
-					break;
-				}
-
-				/* record begin time of next command, and initiate it */
-				if (report_per_command)
-				{
-					st->stmt_begin = pg_time_now_lazy(run);
-				}
-
-				/* Execute the command */
-				if (command->type == SQL_COMMAND)
-				{
-					/* disallow \aset and \gset in pipeline mode */
-					if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
-					{
-						if (command->meta == META_GSET)
-						{
-							commandFailed(st, "gset", "\\gset is not allowed in pipeline mode");
-							st->state = CSTATE_ABORTED;
-							break;
-						}
-						else if (command->meta == META_ASET)
-						{
-							commandFailed(st, "aset", "\\aset is not allowed in pipeline mode");
-							st->state = CSTATE_ABORTED;
-							break;
-						}
-					}
-
-					if (!sendCommand(st, command))
-					{
-						commandFailed(st, "SQL", "SQL command send failed");
-						st->state = CSTATE_ABORTED;
-					}
-					else
-					{
-						/* 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;
-					}
-				}
-				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
-					 */
-					MetaCommandResult mres = executeMetaCommand(run, st);
-
-					if (mres == META_RESULT_SLEEP)
-					{
-						st->state = CSTATE_SLEEP;
-						wakeup_heap_insert(&run->wakeup_heap, st, st->sleep_until);
-						if (run->sockets->batch)
-							remove_socket_from_set(run->sockets, st);
-						return;
-					}
-					else if (mres == META_RESULT_ABORTED)
-					{
-						st->state = CSTATE_ABORTED;
-						st->estatus = ESTATUS_META_COMMAND_ERROR;
-					}
-					else if (mres == META_RESULT_WAIT_RESULT)
-						st->state = CSTATE_WAIT_RESULT;
-					else		/* META_RESULT_END_COMMAND */
-						st->state = CSTATE_END_COMMAND;
-				}
-
-				/*
-				 * We're now waiting for an SQL command to complete, or
-				 * finished processing a metacommand, or need to sleep, or
-				 * something bad happened.
-				 */
-				Assert(st->state == CSTATE_WAIT_RESULT ||
-					   st->state == CSTATE_END_COMMAND ||
-					   st->state == CSTATE_SLEEP ||
-					   st->state == CSTATE_ABORTED);
-				break;
-
-				/*
-				 * non executed conditional branch
-				 */
-			case CSTATE_SKIP_COMMAND:
-				Assert(!conditional_active(st->cstack));
-				/* quickly skip commands until something to do... */
-				skipFalseConditionBranch(st);
-				break;
-
-				/*
-				 * Wait for the current SQL command to complete
-				 */
-			case CSTATE_WAIT_RESULT:
-				pg_log_debug("client %d receiving", st->id);
-
-				/*
-				 * 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.
-				 */
-				if (PQisBusy(st->con) && !PQconsumeInput(st->con))
-				{
-					/* there's something wrong */
-					commandFailed(st, "SQL", "perhaps the backend died while processing");
-					st->state = CSTATE_ABORTED;
-					break;
-				}
-				if (PQisBusy(st->con))
-					return;		/* don't have the whole result yet */
-
-				/* store or discard the query results */
-				if (readCommandResponse(st,
-										sql_script[st->use_file].commands[st->command]->meta,
-										sql_script[st->use_file].commands[st->command]->varprefix))
-				{
-					/*
-					 * outside of pipeline mode: stop reading results.
-					 * pipeline mode: continue reading results until an
-					 * end-of-pipeline response.
-					 */
-					if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
-						st->state = CSTATE_END_COMMAND;
-				}
-				else if (canRetryError(st->estatus) || canContinueOnError(st->estatus))
-					st->state = CSTATE_ERROR;
-				else
-					st->state = CSTATE_ABORTED;
-				break;
-
-				/*
-				 * Wait until sleep is done. This state is entered after a
-				 * \sleep metacommand. The behavior is similar to
-				 * CSTATE_THROTTLE, but proceeds to CSTATE_START_COMMAND
-				 * instead of CSTATE_START_TX.
-				 */
-			case CSTATE_SLEEP:
-				st->state = CSTATE_END_COMMAND;
-				break;
-
-				/*
-				 * End of command: record stats and proceed to next command.
-				 */
-			case CSTATE_END_COMMAND:
-
-				/*
-				 * command completed: accumulate per-command execution times
-				 * in thread-local data structure, if per-command latencies
-				 * are requested.
-				 */
-				if (report_per_command)
-				{
-					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 */
-					addToSimpleStats(&command->stats,
-									 PG_TIME_GET_DOUBLE(now - st->stmt_begin));
-				}
-
-				/* Go ahead with next command, to be executed or skipped */
-				st->command++;
-				st->state = conditional_active(st->cstack) ?
-					CSTATE_START_COMMAND : CSTATE_SKIP_COMMAND;
-				break;
-
-				/*
-				 * Clean up after an error.
-				 */
-			case CSTATE_ERROR:
-				{
-					TStatus		tstatus;
-
-					Assert(st->estatus != ESTATUS_NO_ERROR);
-
-					/* Clear the conditional stack */
-					conditional_stack_reset(st->cstack);
-
-					/* Read and discard until a sync point in pipeline mode */
-					if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
-					{
-						if (!discardUntilSync(st))
-						{
-							st->state = CSTATE_ABORTED;
-							break;
-						}
-					}
-
-					/*
-					 * Check if we have a (failed) transaction block or not,
-					 * and roll it back if any.
-					 */
-					tstatus = getTransactionStatus(st->con);
-					if (tstatus == TSTATUS_IN_BLOCK)
-					{
-						/* Try to rollback a (failed) transaction block. */
-						if (!PQsendQuery(st->con, "ROLLBACK"))
-						{
-							pg_log_error("client %d aborted: failed to send sql command for rolling back the failed transaction",
-										 st->id);
-							st->state = CSTATE_ABORTED;
-						}
-						else
-							st->state = CSTATE_WAIT_ROLLBACK_RESULT;
-					}
-					else if (tstatus == TSTATUS_IDLE)
-					{
-						/*
-						 * If time is over, we're done; otherwise, check if we
-						 * can retry the error.
-						 */
-						st->state = timer_exceeded ? CSTATE_FINISHED :
-							doRetry(run, st) ? CSTATE_RETRY : CSTATE_FAILURE;
-					}
-					else
-					{
-						if (tstatus == TSTATUS_CONN_ERROR)
-							pg_log_error("perhaps the backend died while processing");
-
-						pg_log_error("client %d aborted while receiving the transaction status", st->id);
-						st->state = CSTATE_ABORTED;
-					}
-					break;
-				}
-
-				/*
-				 * Wait for the rollback command to complete
-				 */
-			case CSTATE_WAIT_ROLLBACK_RESULT:
-				{
-					PGresult   *res;
-
-					pg_log_debug("client %d receiving", st->id);
-					if (!PQconsumeInput(st->con))
-					{
-						pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
-									 st->id);
-						st->state = CSTATE_ABORTED;
-						break;
-					}
-					if (PQisBusy(st->con))
-						return; /* don't have the whole result yet */
-
-					/*
-					 * Read and discard the query result;
-					 */
-					res = PQgetResult(st->con);
-					switch (PQresultStatus(res))
-					{
-						case PGRES_COMMAND_OK:
-							/* OK */
-							PQclear(res);
-							/* null must be returned */
-							res = PQgetResult(st->con);
-							Assert(res == NULL);
-
-							/*
-							 * If time is over, we're done; otherwise, check
-							 * if we can retry the error.
-							 */
-							st->state = timer_exceeded ? CSTATE_FINISHED :
-								doRetry(run, st) ? CSTATE_RETRY : CSTATE_FAILURE;
-							break;
-						default:
-							pg_log_error("client %d aborted while rolling back the transaction after an error; %s",
-										 st->id, PQerrorMessage(st->con));
-							PQclear(res);
-							st->state = CSTATE_ABORTED;
-							break;
-					}
-					break;
-				}
-
-				/*
-				 * Retry the transaction after an error.
-				 */
-			case CSTATE_RETRY:
-				command = sql_script[st->use_file].commands[st->command];
-
-				/*
-				 * Inform that the transaction will be retried after the
-				 * error.
-				 */
-				if (verbose_errors)
-					printVerboseErrorMessages(run, st, true);
-
-				/* Count tries and retries */
-				st->tries++;
-				command->retries++;
-
-				/*
-				 * Reset the random state as they were at the beginning of the
-				 * transaction.
-				 */
-				st->cs_func_rs = st->random_state;
-
-				/* Process the first transaction command. */
-				st->command = 0;
-				st->estatus = ESTATUS_NO_ERROR;
-				st->state = CSTATE_START_COMMAND;
-				break;
-
-				/*
-				 * Record a failed transaction.
-				 */
-			case CSTATE_FAILURE:
-				command = sql_script[st->use_file].commands[st->command];
-
-				/* Accumulate the failure. */
-				command->failures++;
-
-				/*
-				 * Inform that the failed transaction will not be retried.
-				 */
-				if (verbose_errors)
-					printVerboseErrorMessages(run, st, false);
-
-				/* End the failed transaction. */
-				st->state = CSTATE_END_TX;
-				break;
-
-				/*
-				 * End of transaction (end of script, really).
-				 */
-			case CSTATE_END_TX:
-				{
-					TStatus		tstatus;
-
-					/* transaction finished: calculate latency and do log */
-					processXactStats(run, st, false);
-
-					/*
-					 * missing \endif... cannot happen if CheckConditional was
-					 * okay
-					 */
-					Assert(conditional_stack_empty(st->cstack));
-
-					/*
-					 * We must complete all the transaction blocks that were
-					 * started in this script.
-					 */
-					tstatus = getTransactionStatus(st->con);
-					if (tstatus == TSTATUS_IN_BLOCK)
-					{
-						pg_log_error("client %d aborted: end of script reached without completing the last transaction",
-									 st->id);
-						st->state = CSTATE_ABORTED;
-						break;
-					}
-					else if (tstatus != TSTATUS_IDLE)
-					{
-						if (tstatus == TSTATUS_CONN_ERROR)
-							pg_log_error("perhaps the backend died while processing");
-
-						pg_log_error("client %d aborted while receiving the transaction status", st->id);
-						st->state = CSTATE_ABORTED;
-						break;
-					}
-
-					if (is_connect)
-					{
-						pg_time_usec_t start = pg_time_now_lazy(run);
-
-						finishCon(run->sockets, st);
-						run->now = pg_time_now();
-						run->thread->conn_duration += run->now - start;
-					}
-
-					if ((st->cnt >= nxacts && duration <= 0) || timer_exceeded)
-					{
-						/* script completed */
-						st->state = CSTATE_FINISHED;
-						break;
-					}
-
-					/* next transaction (script) */
-					st->state = CSTATE_CHOOSE_SCRIPT;
-
-					/*
-					 * Ensure that we always return on this point, so as to
-					 * avoid an infinite loop if the script only contains meta
-					 * commands.
-					 */
-					return;
-				}
-
-				/*
-				 * Final states.  Close the connection if it's still open.
-				 */
-			case CSTATE_ABORTED:
-			case CSTATE_FINISHED:
-
-				/*
-				 * Don't measure the disconnection delays here even if in
-				 * CSTATE_FINISHED and -C/--connect option is specified.
-				 * Because in this case all the connections that this thread
-				 * established are closed at the end of transactions and the
-				 * disconnection delays should have already been measured at
-				 * that moment.
-				 *
-				 * In CSTATE_ABORTED state, the measurement is no longer
-				 * necessary because we cannot report complete results anyways
-				 * in this case.
-				 */
-				finishCon(run->sockets, st);
-				return;
-		}
-	}
+	Assert(!(st->aborted || st->coro_depth == 0));
+	return st->coro_stack[st->coro_depth - 1].func(run, st);
 }
 
 /*
- * Subroutine for advanceConnectionState -- initiate or execute the current
- * meta command, and return the next state to set.
+ * Stackless coroutines: each CState has a stack of Coroutine frames, each
+ * remembering the function and the line to resume at.
+ *
+ * CORO_WAIT() and its variants save __LINE__ as the resume point and return
+ * CORO_YIELD to the scheduler, which goes on to advance other clients.  On
+ * re-entry CORO_DISPATCH() switches on the saved line.  CORO_CALL() pushes a
+ * nested coroutine, CORO_RETURN() pops frames; CORO_DONE from the outermost
+ * frame means the client is finished or aborted.
+ */
+#define CORO_LINE st->coro_stack[st->coro_depth-1].line
+
+#define CORO_DISPATCH() \
+	switch (CORO_LINE) \
+	{ \
+		case 0: do {} while(0)
+
+#define _CORO_WAIT() \
+	CORO_LINE = __LINE__; \
+	return CORO_YIELD; \
+	case __LINE__:
+
+#define CORO_WAIT() do {\
+	CORO_LINE = __LINE__; \
+	return CORO_YIELD; \
+	case __LINE__: ; \
+	} while (0)
+
+#define CORO_SCHED() do {\
+	ready_add(run, st); \
+	_CORO_WAIT(); \
+	} while (0)
+
+#define CORO_SLEEP_TILL(till) do { \
+	/* skip in the past: do not suspend if the deadline has already come */ \
+	if ((till) <= run->now) \
+		break; \
+	wakeup_heap_insert(&run->wakeup_heap, st, (till)); \
+	if (run->sockets->batch) \
+		remove_socket_from_set(run->sockets, st); \
+	_CORO_WAIT() \
+	add_socket_to_set(run->sockets, st); \
+	} while (0)
+
+#define CORO_CALL(func) do { \
+	CORO_LINE = __LINE__; \
+	return coro_invoke(st, func); \
+	case __LINE__: ; \
+	} while(0)
+
+#define CORO_RETURN() \
+	return coro_return(st)
+
+#define CORO_ABORT() \
+	return coro_abort(st)
+
+#define CORO_DISPATCH_END() \
+		break; \
+	default: \
+		pg_fatal("Coroutine line undefined %d", CORO_LINE); \
+	} \
+	return coro_return(st)
+
+static CoroResult waitForResults(RunState *run, CState *st);
+static CoroResult waitForAbort(RunState *run, CState *st);
+static CoroResult discardUntilSync(RunState *run, CState *st);
+
+/*
+ * Run the transactions of one client: choose a script and execute its
+ * commands.
+ *
+ * Note: once a script is started, it will either error or run till its end,
+ * where it may be interrupted.  It is not interrupted while running, so
+ * pgbench --time is to be understood as tx are allowed to start in that
+ * time, and will finish when their work is completed.
+ */
+static CoroResult
+scriptHandling(RunState *run, CState *st)
+{
+	/*
+	 * gettimeofday() isn't free, so the current time lives in run->now (see
+	 * RunState) and is fetched lazily via pg_time_now_lazy().  Keeping the
+	 * same value for one transaction ensures that e.g. the calculated latency
+	 * reported in the log file and in the totals are the same.
+	 */
+	Command    *command;
+	TStatus		tstatus;
+
+	CORO_DISPATCH();
+
+l_restart:
+	if (timer_exceeded || (nxacts > 0 && st->cnt >= nxacts))
+		CORO_RETURN();
+
+	st->use_file = chooseScript(run->thread);
+	Assert(conditional_stack_empty(st->cstack));
+
+	/* reset transaction variables to default values */
+	st->estatus = ESTATUS_NO_ERROR;
+	st->tries = 1;
+
+	pg_log_debug("client %d executing script \"%s\"",
+				 st->id, sql_script[st->use_file].desc);
+
+	if (throttle_delay > 0)
+	{
+		/*
+		 * Generate a delay such that the series of delays will approximate a
+		 * Poisson distribution centered on the throttle_delay time.
+		 *
+		 * If transactions are too slow or a given wait is shorter than a
+		 * transaction, the next transaction will start right away.
+		 */
+
+l_recalc_throttle:
+		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 so that
+		 * the transaction will miss the latency limit even if it completed
+		 * immediately, skip this time slot and loop to reschedule.
+		 */
+		if (latency_limit)
+		{
+			pg_time_usec_t now = pg_time_now_lazy(run);
+
+			if (run->thread->throttle_trigger < now - latency_limit)
+			{
+				processXactStats(run, st, true);
+
+				/*
+				 * Finish client if -T or -t was exceeded.
+				 *
+				 * Stop counting skipped transactions under -T as soon as the
+				 * timer is exceeded. Because otherwise it can take a very
+				 * long time to count all of them especially when quite a lot
+				 * of them happen with unrealistically high rate setting in
+				 * -R, which would prevent pgbench from ending immediately.
+				 * Because of this behavior, note that there is no guarantee
+				 * that all skipped transactions are counted under -T though
+				 * there is under -t. This is OK in practice because it's very
+				 * unlikely to happen with realistic setting.
+				 */
+				if (timer_exceeded || (nxacts > 0 && st->cnt >= nxacts))
+					CORO_RETURN();
+
+				goto l_recalc_throttle;
+			}
+		}
+
+		/*
+		 * stop client if next transaction is beyond pgbench end of execution;
+		 * otherwise, throttle it.
+		 */
+		if (end_time > 0 && st->txn_scheduled > end_time)
+			CORO_RETURN();
+
+		CORO_SLEEP_TILL(st->txn_scheduled);
+
+		if (timer_exceeded)
+			CORO_RETURN();
+	}
+
+	/* establish connection if needed, i.e. under --connect */
+	if (st->con == NULL)
+	{
+		pg_time_usec_t start = 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();
+		}
+
+		/* reset now after connection */
+		run->now = pg_time_now();
+
+		run->thread->conn_duration += run->now - start;
+
+		/* Reset session-local state */
+		pg_free(st->prepared);
+		st->prepared = NULL;
+	}
+
+	/*
+	 * It is the first try to run this transaction. Remember the random state:
+	 * maybe it will get an error and we will need to run it again.
+	 */
+	st->random_state = st->cs_func_rs;
+
+	/* record transaction start time */
+	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 = st->txn_begin;
+
+	/* Begin with the first command */
+	st->command = 0;
+
+l_start_command:
+	add_socket_to_set(run->sockets, st);
+	command = sql_script[st->use_file].commands[st->command];
+
+	/*
+	 * Transition to script end processing if done, but close up shop if a
+	 * pipeline is open at this point.
+	 */
+	if (command == NULL)
+	{
+		if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
+			goto l_end_tx;
+		else
+		{
+			pg_log_error("client %d aborted: end of script reached with pipeline open",
+						 st->id);
+			CORO_ABORT();
+		}
+	}
+
+	/* record begin time of next command, and initiate it */
+	if (report_per_command)
+	{
+		st->stmt_begin = pg_time_now_lazy(run);
+	}
+
+	/* Execute the command */
+	if (command->type == SQL_COMMAND)
+	{
+		/* disallow \aset and \gset in pipeline mode */
+		if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
+		{
+			if (command->meta == META_GSET)
+			{
+				commandFailed(st, "gset", "\\gset is not allowed in pipeline mode");
+				CORO_ABORT();
+			}
+			else if (command->meta == META_ASET)
+			{
+				commandFailed(st, "aset", "\\aset is not allowed in pipeline mode");
+				CORO_ABORT();
+			}
+		}
+
+		if (!sendCommand(st, command))
+		{
+			commandFailed(st, "SQL", "SQL command send failed");
+			CORO_ABORT();
+		}
+		else if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
+			CORO_CALL(waitForResults);
+	}
+	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
+		 */
+		MetaCommandResult mres = executeMetaCommand(run, st);
+
+		if (mres == 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)
+		goto l_error;
+
+	/*
+	 * command completed: accumulate per-command execution times in
+	 * thread-local data structure, if per-command latencies are requested.
+	 */
+	if (report_per_command)
+	{
+		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 */
+		addToSimpleStats(&command->stats,
+						 PG_TIME_GET_DOUBLE(now - st->stmt_begin));
+	}
+
+	/* Go ahead with next command, to be executed or skipped */
+	st->command++;
+	if (!conditional_active(st->cstack))
+		skipFalseConditionBranch(st);
+	goto l_start_command;
+
+l_end_tx:
+	/* transaction finished: calculate latency and do log */
+	processXactStats(run, st, false);
+
+	/*
+	 * missing \endif... cannot happen if CheckConditional was okay
+	 */
+	Assert(conditional_stack_empty(st->cstack));
+
+	/*
+	 * We must complete all the transaction blocks that were started in this
+	 * script.
+	 */
+	tstatus = getTransactionStatus(st->con);
+	if (tstatus == TSTATUS_IN_BLOCK)
+	{
+		pg_log_error("client %d aborted: end of script reached without completing the last transaction",
+					 st->id);
+		CORO_ABORT();
+	}
+	else if (tstatus != TSTATUS_IDLE)
+	{
+		if (tstatus == TSTATUS_CONN_ERROR)
+			pg_log_error("perhaps the backend died while processing");
+
+		pg_log_error("client %d aborted while receiving the transaction status", st->id);
+		CORO_ABORT();
+	}
+
+	if (is_connect)
+	{
+		pg_time_usec_t start = pg_time_now_lazy(run);
+
+		finishCon(run->sockets, st);
+		run->now = pg_time_now();
+		run->thread->conn_duration += run->now - start;
+	}
+
+	/* next transaction (script) */
+	CORO_SCHED();
+	goto l_restart;
+
+l_error:
+	Assert(st->estatus != ESTATUS_NO_ERROR);
+
+	/* Clear the conditional stack */
+	conditional_stack_reset(st->cstack);
+
+	/* Read and discard until a sync point in pipeline mode */
+	if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
+		CORO_CALL(discardUntilSync);
+
+	/*
+	 * Check if we have a (failed) transaction block or not, and roll it back
+	 * if any.
+	 */
+	tstatus = getTransactionStatus(st->con);
+	if (tstatus == TSTATUS_IDLE)
+		goto l_failure;
+	if (tstatus != TSTATUS_IN_BLOCK)
+	{
+		if (tstatus == TSTATUS_CONN_ERROR)
+			pg_log_error("perhaps the backend died while processing");
+
+		pg_log_error("client %d aborted while receiving the transaction status", st->id);
+		CORO_ABORT();
+	}
+
+	/* Try to rollback a (failed) transaction block. */
+	if (!PQsendQuery(st->con, "ROLLBACK"))
+	{
+		pg_log_error("client %d aborted: failed to send sql command for rolling back the failed transaction",
+					 st->id);
+		CORO_ABORT();
+	}
+
+	CORO_CALL(waitForAbort);
+
+l_failure:
+	if (timer_exceeded)
+		CORO_RETURN();
+	command = sql_script[st->use_file].commands[st->command];
+
+	if (doRetry(run, st))
+	{
+
+		/*
+		 * Inform that the transaction will be retried after the error.
+		 */
+		if (verbose_errors)
+			printVerboseErrorMessages(run, st, true);
+
+		/* Count tries and retries */
+		st->tries++;
+		command->retries++;
+
+		/*
+		 * Reset the random state as they were at the beginning of the
+		 * transaction.
+		 */
+		st->cs_func_rs = st->random_state;
+
+		/* Process the first transaction command. */
+		st->command = 0;
+		st->estatus = ESTATUS_NO_ERROR;
+		goto l_start_command;
+	}
+	else
+	{
+		/* Accumulate the failure. */
+		command->failures++;
+
+		/*
+		 * Inform that the failed transaction will not be retried.
+		 */
+		if (verbose_errors)
+			printVerboseErrorMessages(run, st, false);
+
+		/* End the failed transaction. */
+		goto l_end_tx;
+	}
+
+	CORO_DISPATCH_END();
+}
+
+static CoroResult
+waitForResults(RunState *run, CState *st)
+{
+	CORO_DISPATCH();
+
+	do
+	{
+		while (PQisBusy(st->con))
+		{
+			pg_log_debug("client %d receiving", st->id);
+
+			/*
+			 * 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.
+			 */
+			if (!PQconsumeInput(st->con))
+			{
+				/* there's something wrong */
+				commandFailed(st, "SQL", "perhaps the backend died while processing");
+				CORO_ABORT();
+			}
+			if (PQisBusy(st->con))
+				CORO_WAIT();	/* don't have the whole result yet */
+		}
+
+		/* store or discard the query results */
+		if (!readCommandResponse(st,
+								 sql_script[st->use_file].commands[st->command]->meta,
+								 sql_script[st->use_file].commands[st->command]->varprefix))
+		{
+			if (canRetryError(st->estatus) || canContinueOnError(st->estatus))
+				CORO_RETURN();
+			CORO_ABORT();
+		}
+
+		/*
+		 * outside of pipeline mode: stop reading results. pipeline mode:
+		 * continue reading results until an end-of-pipeline response.
+		 */
+	} while (PQpipelineStatus(st->con) == PQ_PIPELINE_ON);
+
+	CORO_DISPATCH_END();
+}
+
+static CoroResult
+waitForAbort(RunState *run, CState *st)
+{
+	PGresult   *res;
+
+	CORO_DISPATCH();
+
+	while (PQisBusy(st->con))
+	{
+		pg_log_debug("client %d receiving", st->id);
+
+		/*
+		 * 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.
+		 */
+		if (!PQconsumeInput(st->con))
+		{
+			/* there's something wrong */
+			pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
+						 st->id);
+			CORO_ABORT();
+		}
+		if (PQisBusy(st->con))
+			CORO_WAIT();		/* don't have the whole result yet */
+	}
+
+	/*
+	 * Read and discard the query result;
+	 */
+	res = PQgetResult(st->con);
+	if (PQresultStatus(res) != PGRES_COMMAND_OK)
+	{
+		pg_log_error("client %d aborted while rolling back the transaction after an error; %s",
+					 st->id, PQerrorMessage(st->con));
+		PQclear(res);
+		CORO_ABORT();
+	}
+	/* OK */
+	PQclear(res);
+	/* null must be returned */
+	res = PQgetResult(st->con);
+	Assert(res == NULL);
+
+	CORO_DISPATCH_END();
+}
+
+/*
+ * Read and discard results until the last sync point.
+ */
+static CoroResult
+discardUntilSync(RunState *run, CState *st)
+{
+	PGresult   *res;
+
+	CORO_DISPATCH();
+
+	st->received_sync = false;
+
+	/*
+	 * Send a Sync message to ensure at least one PGRES_PIPELINE_SYNC is
+	 * received and to avoid an infinite loop, since all earlier ones may have
+	 * already been received.
+	 */
+	if (!PQpipelineSync(st->con))
+	{
+		pg_log_error("client %d aborted: failed to send a pipeline sync",
+					 st->id);
+		CORO_ABORT();
+	}
+
+	/*
+	 * Continue reading results until the last sync point, i.e., until
+	 * reaching null just after PGRES_PIPELINE_SYNC.
+	 */
+	do
+	{
+		while (PQisBusy(st->con))
+		{
+			pg_log_debug("client %d receiving", st->id);
+
+			/*
+			 * 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.
+			 */
+			if (!PQconsumeInput(st->con))
+			{
+				/* there's something wrong */
+				pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
+							 st->id);
+				CORO_ABORT();
+			}
+			if (PQisBusy(st->con))
+				CORO_WAIT();	/* don't have the whole result yet */
+		}
+
+		while ((res = PQgetResult(st->con)) != NULL)
+		{
+			if (PQstatus(st->con) == CONNECTION_BAD)
+			{
+				pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
+							 st->id);
+				PQclear(res);
+				CORO_ABORT();
+			}
+
+			if (PQresultStatus(res) == PGRES_PIPELINE_SYNC)
+				st->received_sync = true;
+			else
+
+				/*
+				 * If a PGRES_PIPELINE_SYNC is followed by something other
+				 * than PGRES_PIPELINE_SYNC or NULL, another
+				 * PGRES_PIPELINE_SYNC will appear later. Reset received_sync
+				 * to false to wait for it.
+				 */
+				st->received_sync = false;
+			PQclear(res);
+		}
+	} while (!st->received_sync);
+
+	/*
+	 * Reset ongoing sync count to 0 since all PGRES_PIPELINE_SYNC results
+	 * have been discarded.
+	 */
+	st->num_syncs = 0;
+
+	/* exit pipeline */
+	if (PQexitPipelineMode(st->con) != 1)
+	{
+		pg_log_error("client %d aborted: failed to exit pipeline mode for rolling back the failed transaction",
+					 st->id);
+		CORO_ABORT();
+	}
+
+	CORO_DISPATCH_END();
+}
+
+/*
+ * Execute the current meta command.  \sleep, \startpipeline and \endpipeline,
+ * which may suspend, are handled by metaCommandHandling() instead.
+ *
+ * Returns META_RESULT_END_COMMAND, or META_RESULT_ABORTED on error.
  *
  * run->now is updated to the current time, unless the command is expected
  * to take no time to execute.
@@ -4670,7 +4558,7 @@ skipFalseConditionBranch(CState *st)
 {
 	Command    *command;
 
-	while (st->state == CSTATE_SKIP_COMMAND)
+	while (!conditional_active(st->cstack))
 	{
 		command = sql_script[st->use_file].commands[st->command];
 
@@ -4704,23 +4592,20 @@ skipFalseConditionBranch(CState *st)
 				else if (command->meta == META_ELIF)
 				{
 					/* we must evaluate the condition */
-					st->state = CSTATE_START_COMMAND;
+					return;
 				}
 				else if (command->meta == META_ELSE)
 				{
 					/* we must execute next command */
 					conditional_stack_poke(st->cstack,
 										   IFSTATE_ELSE_TRUE);
-					st->state = CSTATE_START_COMMAND;
 					st->command++;
+					return;
 				}
 				else if (command->meta == META_ENDIF)
 				{
 					Assert(!conditional_stack_empty(st->cstack));
 					conditional_stack_pop(st->cstack);
-					if (conditional_active(st->cstack))
-						st->state = CSTATE_START_COMMAND;
-					/* else state remains CSTATE_SKIP_COMMAND */
 					st->command++;
 				}
 				break;
@@ -4734,8 +4619,6 @@ skipFalseConditionBranch(CState *st)
 				{
 					Assert(!conditional_stack_empty(st->cstack));
 					conditional_stack_pop(st->cstack);
-					if (conditional_active(st->cstack))
-						st->state = CSTATE_START_COMMAND;
 				}
 				/* could detect "else" & "elif" after "else" */
 				st->command++;
@@ -7704,7 +7587,7 @@ main(int argc, char **argv)
 			THREAD_JOIN(thread->thread);
 
 		for (int j = 0; j < thread->nstate; j++)
-			if (thread->state[j].state != CSTATE_FINISHED)
+			if (!thread->state[j].finished)
 				exit_code = 2;
 
 		/* aggregate thread level stats */
@@ -7785,13 +7668,16 @@ threadRun(void *arg)
 			pg_fatal("could not open logfile \"%s\": %m", logpath);
 	}
 
-	/* explicitly initialize the state machines */
+	/*
+	 * 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++)
 	{
-		state[i].state = CSTATE_CHOOSE_SCRIPT;
-		state[i].sockidx = -1;
+		coro_invoke(&state[i], scriptHandling);
 		ready_add(&run, &state[i]);
+		state[i].sockidx = -1;
 	}
 
 	/* READY */
@@ -7946,28 +7832,32 @@ threadRun(void *arg)
 		while (ready != NULL)
 		{
 			CState	   *next = ready->next_ready;
+			CoroResult	res;
 
 			ready->is_ready = false;
 
-			advanceConnectionState(&run, ready);
+			do
+				res = advanceConnectionState(&run, ready);
+			while (res == CORO_CONTINUE);
 
 			/*
-			 * If --exit-on-abort is used, the program is going to exit when
-			 * any client is aborted.
+			 * If the client's coroutine is done (finished or aborted), that's
+			 * one fewer client that remains.
 			 */
-			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 (ready->state == CSTATE_FINISHED ||
-					 ready->state == CSTATE_ABORTED)
+			if (res == CORO_DONE)
+			{
+				/*
+				 * If --exit-on-abort is used, the program is going to exit
+				 * when any client is aborted.
+				 */
+				if (exit_on_abort && ready->aborted)
+					goto done;
+				if (!ready->aborted)
+					ready->finished = true;
+				if (!timer_exceeded)
+					finishCon(run.sockets, ready);
 				remains--;
-			else if (STATE_IS_ACTIVE(ready->state))
-				/* client is still active, so it needs to be processed */
-				ready_add(&run, ready);
+			}
 
 			ready = next;
 		}
@@ -8009,7 +7899,7 @@ done:
 		 */
 		for (int i = 0; i < nstate; i++)
 		{
-			if (state[i].state != CSTATE_FINISHED)
+			if (!state[i].finished)
 			{
 				pg_log_error("Run was aborted due to an error in thread %d",
 							 thread->tid);
@@ -8313,6 +8203,12 @@ add_socket_to_set(socket_set *sa, CState *st)
 {
 	int			fd = PQsocket(st->con);
 
+	if (fd < 0)
+	{
+		Assert(st->sockidx == -1);
+		return;
+	}
+
 	/*
 	 * Adding a client that is already in the set (sockidx >= 0) is a no-op,
 	 * so callers can invoke it unconditionally.
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index d85d44752bc..35f95ab41b5 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -559,6 +559,9 @@ CopyStmt
 CopyToRoutine
 CopyToState
 CopyToStateData
+CoroFunc
+CoroResult
+Coroutine
 Cost
 CostSelector
 Counters
-- 
2.43.0

