From be2d4818df1286660e6eb69cc2a94c7537056421 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Tue, 24 Nov 2026 11:44:41 -0500
Subject: [PATCH v1-PoC-buffer 2/2] Allow parallel plans for the SELECT input
 of INSERT

Keep the source subquery separate from INSERT so that its read side can
use parallel query without running defaults, triggers, conflict
handling, or RETURNING expressions in parallel mode.  Place a
TupleBuffer above a parallel source and shut down its workers before
returning the first row, including when a LIMIT stops a Gather early.

After setrefs chooses among alternative subplans, buffer only if a
Gather or Gather Merge remains reachable, including through initplans
and expression SubPlans.  Otherwise pass rows through without storing
them.  Gate the feature with enable_insert_select_parallel, off by
default.
---
 doc/src/sgml/config.sgml                      |  21 ++
 doc/src/sgml/parallel.sgml                    |  11 +-
 src/backend/executor/execMain.c               |  10 +
 src/backend/optimizer/path/allpaths.c         |  36 ++++
 src/backend/optimizer/plan/planner.c          |  99 ++++++---
 src/backend/optimizer/plan/setrefs.c          | 106 ++++++++++
 src/backend/optimizer/prep/prepjointree.c     |   5 +
 src/backend/utils/misc/guc_parameters.dat     |   7 +
 src/backend/utils/misc/postgresql.conf.sample |   1 +
 src/include/optimizer/optimizer.h             |   1 +
 src/include/optimizer/planmain.h              |   1 +
 src/test/regress/expected/sysviews.out        |   3 +-
 src/test/regress/expected/write_parallel.out  | 198 ++++++++++++++++++
 src/test/regress/sql/write_parallel.sql       |  84 ++++++++
 14 files changed, 547 insertions(+), 36 deletions(-)

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 28440932a73..c6976126c45 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -6087,6 +6087,27 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-enable-insert-select-parallel" xreflabel="enable_insert_select_parallel">
+      <term><varname>enable_insert_select_parallel</varname> (<type>boolean</type>)
+      <indexterm>
+       <primary><varname>enable_insert_select_parallel</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Allows the planner to use a parallel plan for the <command>SELECT</command>
+        part of <command>INSERT ... SELECT</command>.  When it chooses such a
+        plan, a <literal>TupleBuffer</literal> node collects all source rows
+        before insertion begins.  This can use temporary disk space if the
+        rows exceed <xref linkend="guc-work-mem"/>.  If a parallel subplan is
+        considered but discarded, <command>EXPLAIN</command> may still show
+        a <literal>TupleBuffer</literal> with <literal>Buffering: false</literal>;
+        it passes rows through without storing them.  The insert itself is
+        always serial.  The default is <literal>off</literal>.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="guc-enable-material" xreflabel="enable_material">
       <term><varname>enable_material</varname> (<type>boolean</type>)
       <indexterm>
diff --git a/doc/src/sgml/parallel.sgml b/doc/src/sgml/parallel.sgml
index af43484703e..35153fb4bde 100644
--- a/doc/src/sgml/parallel.sgml
+++ b/doc/src/sgml/parallel.sgml
@@ -163,6 +163,13 @@ EXPLAIN SELECT * FROM pgbench_accounts WHERE filler LIKE '%x%';
           </listitem>
         </itemizedlist>
       </para>
+      <para>
+        When <xref linkend="guc-enable-insert-select-parallel"/> is enabled,
+        <command>INSERT ... SELECT</command> can also use a parallel plan for
+        its source query.  In that case the leader buffers all source rows and
+        shuts down the parallel workers before inserting any rows.  Queries
+        with a data-modifying CTE or row locking in the source are not eligible.
+      </para>
     </listitem>
 
     <listitem>
@@ -185,7 +192,9 @@ EXPLAIN SELECT * FROM pgbench_accounts WHERE filler LIKE '%x%';
         Most system-defined functions are <literal>PARALLEL SAFE</literal>,
         but user-defined functions are marked <literal>PARALLEL
         UNSAFE</literal> by default. See the discussion of
-        <xref linkend="parallel-safety"/>.
+        <xref linkend="parallel-safety"/>.  For <command>INSERT ... SELECT</command>,
+        this restriction applies to the source query, not to expressions
+        evaluated during insertion.
       </para>
     </listitem>
 
diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c
index cfe1c2a801b..61e152a05dd 100644
--- a/src/backend/executor/execMain.c
+++ b/src/backend/executor/execMain.c
@@ -1748,6 +1748,16 @@ ExecutePlan(QueryDesc *queryDesc,
 		use_parallel_mode = queryDesc->plannedstmt->parallelModeNeeded;
 	queryDesc->already_executed = true;
 
+	/*
+	 * For INSERT ... SELECT, only the TupleBuffer's fill may launch workers.
+	 * Don't impose parallel-mode restrictions on ModifyTable, including its
+	 * BEFORE STATEMENT triggers, which run before the first source tuple is
+	 * requested.
+	 */
+	estate->es_parallel_insert_select = use_parallel_mode && operation == CMD_INSERT;
+	if (estate->es_parallel_insert_select)
+		use_parallel_mode = false;
+
 	estate->es_use_parallel_mode = use_parallel_mode;
 	if (use_parallel_mode)
 		EnterParallelMode();
diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index dab387c1666..54221c74670 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -2689,6 +2689,9 @@ set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
 {
 	Query	   *parse = root->parse;
 	Query	   *subquery = rte->subquery;
+	ParallelInsertInfo *insert = root->glob->parallelInsert;
+	bool		insert_source = insert && root->query_level == 1 &&
+		rti == insert->source_rti;
 	bool		trivial_pathtarget;
 	Relids		required_outer;
 	pushdown_safety_info safetyInfo;
@@ -2838,11 +2841,29 @@ set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
 	/* plan_params should not be in use in current query level */
 	Assert(root->plan_params == NIL);
 
+	/*
+	 * Only this subquery, not the INSERT's defaults, RETURNING list, etc.,
+	 * may use parallel mode.  Check the actual source after CTE inlining.
+	 */
+	if (insert_source)
+	{
+		Assert(!root->glob->parallelModeOK && !root->glob->parallelModeNeeded);
+		root->glob->maxParallelHazard = max_parallel_hazard(subquery);
+		root->glob->parallelModeOK =
+			root->glob->maxParallelHazard != PROPARALLEL_UNSAFE;
+	}
+
 	/* Generate a subroot and Paths for the subquery */
 	plan_name = choose_plan_name(root->glob, rte->eref->aliasname, false);
 	rel->subroot = subquery_planner(root->glob, subquery, plan_name,
 									root, NULL, false, tuple_fraction, NULL);
 
+	if (insert_source)
+	{
+		root->glob->parallelModeOK = false;
+		root->glob->maxParallelHazard = PROPARALLEL_UNSAFE;
+	}
+
 	/* Isolate the params needed by this specific subplan */
 	rel->subplan_params = root->plan_params;
 	root->plan_params = NIL;
@@ -2906,6 +2927,21 @@ set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
 		Path	   *subpath = (Path *) lfirst(lc);
 		List	   *pathkeys;
 
+		/*
+		 * An INSERT consumes the entire source.  Reserve a place for a buffer
+		 * above the chosen source path, below any INSERT-side projection.
+		 * Don't build the plan here: parallelModeNeeded is set when a Gather
+		 * or Gather Merge plan is built, not when its path is created.
+		 * create_tuplebuffer_plan() checks the flag after building its child.
+		 */
+		if (insert_source)
+		{
+			if (subpath != sub_final_rel->cheapest_total_path)
+				continue;
+			subpath = (Path *) create_tuplebuffer_path(subpath->parent,
+													   subpath, true);
+		}
+
 		/* Convert subpath's pathkeys to outer representation */
 		pathkeys = convert_subquery_pathkeys(root,
 											 rel,
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 568a1b2a346..449d7b66a97 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -68,6 +68,7 @@
 double		cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
 int			debug_parallel_query = DEBUG_PARALLEL_OFF;
 bool		parallel_leader_participation = true;
+bool		enable_insert_select_parallel = false;
 bool		enable_distinct_reordering = true;
 
 /* Hook for plugins to get control in planner() */
@@ -153,6 +154,7 @@ typedef struct
 } preprocess_subquery_phvs_context;
 
 /* Local functions */
+static ParallelInsertInfo *parallel_insert_select_info(Query *parse);
 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
 static Bitmapset *find_having_conflicts(Query *parse, Index group_rtindex);
@@ -364,9 +366,7 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	RelOptInfo *final_rel;
 	Path	   *best_path;
 	Plan	   *top_plan;
-	ListCell   *lp,
-			   *lr,
-			   *lc;
+	ListCell   *lc;
 
 	/*
 	 * Set up global state for this planner invocation.  This data is needed
@@ -410,11 +410,13 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	 * (Note that we do allow CREATE TABLE AS, SELECT INTO, and CREATE
 	 * MATERIALIZED VIEW to use parallel plans, but this is safe only because
 	 * the command is writing into a completely new table which workers won't
-	 * be able to see.  If the workers could see the table, the fact that
-	 * group locking would cause them to ignore the leader's heavyweight GIN
-	 * page locks would make this unsafe.  We'll have to fix that somehow if
-	 * we want to allow parallel inserts in general; updates and deletes have
-	 * additional problems especially around combo CIDs.)
+	 * be able to see.  INSERT ... SELECT is a separate exception: we can
+	 * finish its SELECT before inserting anything.  If reads and writes
+	 * overlapped on a table visible to workers, the fact that group locking
+	 * would cause them to ignore the leader's heavyweight GIN page locks
+	 * would make this unsafe.  We'll have to fix that somehow if we want to
+	 * allow parallel inserts in general; updates and deletes have additional
+	 * problems especially around combo CIDs.)
 	 *
 	 * For now, we don't try to use parallel mode if we're running inside a
 	 * parallel worker.  We might eventually be able to relax this
@@ -423,21 +425,20 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	 */
 	if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
 		IsUnderPostmaster &&
-		parse->commandType == CMD_SELECT &&
 		!parse->hasModifyingCTE &&
 		max_parallel_workers_per_gather > 0 &&
 		!IsParallelWorker())
 	{
-		/* all the cheap tests pass, so scan the query tree */
-		glob->maxParallelHazard = max_parallel_hazard(parse);
-		glob->parallelModeOK = (glob->maxParallelHazard != PROPARALLEL_UNSAFE);
+		if (parse->commandType == CMD_SELECT)
+		{
+			glob->maxParallelHazard = max_parallel_hazard(parse);
+			glob->parallelModeOK = (glob->maxParallelHazard != PROPARALLEL_UNSAFE);
+		}
+		else if (parse->commandType == CMD_INSERT && enable_insert_select_parallel)
+			glob->parallelInsert = parallel_insert_select_info(parse);
 	}
-	else
-	{
-		/* skip the query tree scan, just assume it's unsafe */
+	if (!glob->parallelModeOK)
 		glob->maxParallelHazard = PROPARALLEL_UNSAFE;
-		glob->parallelModeOK = false;
-	}
 
 	/*
 	 * glob->parallelModeNeeded is normally set to false here and changed to
@@ -448,13 +449,14 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	 * regress, then we impose parallel mode whenever it's safe to do so, even
 	 * if the final plan doesn't use parallelism.  It's not safe to do so if
 	 * the query contains anything parallel-unsafe; parallelModeOK will be
-	 * false in that case.  Note that parallelModeOK can't change after this
-	 * point. Otherwise, everything in the query is either parallel-safe or
-	 * parallel-restricted, and in either case it should be OK to impose
-	 * parallel-mode restrictions.  If that ends up breaking something, then
-	 * either some function the user included in the query is incorrectly
-	 * labeled as parallel-safe or parallel-restricted when in reality it's
-	 * parallel-unsafe, or else the query planner itself has a bug.
+	 * false in that case.  In particular, don't force parallel mode for an
+	 * INSERT, even if its SELECT can use it.  Otherwise, everything in the
+	 * query is either parallel-safe or parallel-restricted, and in either
+	 * case it should be OK to impose parallel-mode restrictions.  If that
+	 * ends up breaking something, then either some function the user included
+	 * in the query is incorrectly labeled as parallel-safe or
+	 * parallel-restricted when in reality it's parallel-unsafe, or else the
+	 * query planner itself has a bug.
 	 */
 	glob->parallelModeNeeded = glob->parallelModeOK &&
 		(debug_parallel_query != DEBUG_PARALLEL_OFF);
@@ -634,6 +636,9 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	 */
 	if (glob->paramExecTypes != NIL)
 	{
+		ListCell   *lp,
+				   *lr;
+
 		Assert(list_length(glob->subplans) == list_length(glob->subroots));
 		forboth(lp, glob->subplans, lr, glob->subroots)
 		{
@@ -651,16 +656,7 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	Assert(glob->finalrowmarks == NIL);
 	Assert(glob->resultRelations == NIL);
 	Assert(glob->appendRelations == NIL);
-	top_plan = set_plan_references(root, top_plan);
-	/* ... and the subplans (both regular subplans and initplans) */
-	Assert(list_length(glob->subplans) == list_length(glob->subroots));
-	forboth(lp, glob->subplans, lr, glob->subroots)
-	{
-		Plan	   *subplan = (Plan *) lfirst(lp);
-		PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
-
-		lfirst(lp) = set_plan_references(subroot, subplan);
-	}
+	top_plan = set_stmt_references(root, top_plan);
 
 	/* build the PlannedStmt result */
 	result = makeNode(PlannedStmt);
@@ -741,6 +737,41 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	return result;
 }
 
+/*
+ * Identify the SELECT that transformInsertStmt put in the INSERT's FROM
+ * list.  Don't mistake VALUES or more complex products of rule rewriting for
+ * such a source.  CTEs belonging to the INSERT can be evaluated on demand
+ * inside the SELECT, so they too must be safe to run in parallel mode.
+ */
+static ParallelInsertInfo *
+parallel_insert_select_info(Query *parse)
+{
+	ParallelInsertInfo *info;
+	RangeTblRef *rtr;
+	RangeTblEntry *rte;
+
+	if (list_length(parse->jointree->fromlist) != 1 ||
+		!IsA(linitial(parse->jointree->fromlist), RangeTblRef) ||
+		parse->jointree->quals)
+		return NULL;
+	rtr = linitial_node(RangeTblRef, parse->jointree->fromlist);
+	rte = rt_fetch(rtr->rtindex, parse->rtable);
+	if (rte->rtekind != RTE_SUBQUERY || rte->lateral || rte->securityQuals ||
+		rte->subquery->commandType != CMD_SELECT ||
+		rte->subquery->hasModifyingCTE)
+		return NULL;
+
+	foreach_node(CommonTableExpr, cte, parse->cteList)
+	{
+		if (max_parallel_hazard(castNode(Query, cte->ctequery)) == PROPARALLEL_UNSAFE)
+			return NULL;
+	}
+
+	info = palloc0_object(ParallelInsertInfo);
+	info->source_rti = rtr->rtindex;
+	return info;
+}
+
 
 /*--------------------
  * subquery_planner
diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c
index 9257b54a215..3188b145bb8 100644
--- a/src/backend/optimizer/plan/setrefs.c
+++ b/src/backend/optimizer/plan/setrefs.c
@@ -19,6 +19,7 @@
 #include "catalog/pg_type.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
+#include "optimizer/cost.h"
 #include "optimizer/optimizer.h"
 #include "optimizer/pathnode.h"
 #include "optimizer/planmain.h"
@@ -221,6 +222,90 @@ static void record_elided_node(PlannerGlobal *glob, int plan_node_id,
  *
  *****************************************************************************/
 
+/*
+ * Fix references in the main plan and its subplans.  For a buffered INSERT,
+ * check whether a Gather actually survived selection of AlternativeSubPlans.
+ * Choosing an alternative happens here, later than path and plan creation.
+ */
+Plan *
+set_stmt_references(PlannerInfo *root, Plan *plan)
+{
+	PlannerGlobal *glob = root->glob;
+	ParallelInsertInfo *insert = glob->parallelInsert;
+	bool		check_parallel = insert && glob->parallelModeNeeded;
+	Bitmapset  *parallel_plans = NULL;
+	Bitmapset  *main_deps = NULL;
+	ListCell   *lp,
+			   *lr;
+
+	plan = set_plan_references(root, plan);
+	if (check_parallel)
+	{
+		main_deps = insert->plan_deps;
+		parallel_plans = bms_make_singleton(0);
+	}
+
+	Assert(list_length(glob->subplans) == list_length(glob->subroots));
+	forboth(lp, glob->subplans, lr, glob->subroots)
+	{
+		Plan	   *subplan = (Plan *) lfirst(lp);
+		PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
+
+		if (check_parallel)
+			insert->plan_deps = NULL;
+		lfirst(lp) = set_plan_references(subroot, subplan);
+
+		/* Subplans are built before any plan that references them. */
+		if (check_parallel && bms_overlap(parallel_plans, insert->plan_deps))
+			parallel_plans = bms_add_member(parallel_plans,
+											foreach_current_index(lp) + 1);
+	}
+
+	if (check_parallel)
+	{
+		TupleBuffer *buffer = insert->buffer;
+
+		/*
+		 * All AlternativeSubPlans have now been resolved.  Count only Gathers
+		 * reachable from the main plan, including via initplans and SubPlans.
+		 * If the only Gather was in a discarded alternative, keep the node
+		 * but let the INSERT read its input directly, without a tuplestore or
+		 * parallel mode.
+		 */
+		glob->parallelModeNeeded = bms_overlap(parallel_plans, main_deps);
+		if (buffer && !glob->parallelModeNeeded)
+			buffer->mode = TUPLEBUFFER_PASSTHROUGH;
+		else if (buffer)
+		{
+			Plan	   *bplan = &buffer->plan;
+			Cost		startup_cost;
+			Cost		total_cost;
+
+			/*
+			 * So far the INSERT path has only been charged for its source.
+			 * Add the fill and replay costs to the buffer, the INSERT, and
+			 * any intervening projection or SubqueryScan.
+			 */
+			cost_tuplebuffer(&startup_cost, &total_cost, bplan->total_cost,
+							 bplan->plan_rows, bplan->plan_width);
+			for (Plan *p = plan; p != bplan;)
+			{
+				Assert(p != NULL);
+				p->startup_cost += startup_cost - bplan->startup_cost;
+				p->total_cost += total_cost - bplan->total_cost;
+				if (IsA(p, SubqueryScan))
+					p = ((SubqueryScan *) p)->subplan;
+				else
+					p = outerPlan(p);
+			}
+			bplan->startup_cost = startup_cost;
+			bplan->total_cost = total_cost;
+		}
+	}
+
+	return plan;
+}
+
 /*
  * set_plan_references
  *
@@ -647,6 +732,14 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
 	/* Assign this node a unique ID. */
 	plan->plan_node_id = root->glob->lastPlanNodeId++;
 
+	if (plan->initPlan && root->glob->parallelInsert && root->glob->parallelModeNeeded)
+	{
+		ParallelInsertInfo *insert = root->glob->parallelInsert;
+
+		foreach_node(SubPlan, splan, plan->initPlan)
+			insert->plan_deps = bms_add_member(insert->plan_deps, splan->plan_id);
+	}
+
 	/*
 	 * Plan-type-specific fixes
 	 */
@@ -883,6 +976,10 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
 		case T_Gather:
 		case T_GatherMerge:
 			{
+				ParallelInsertInfo *insert = root->glob->parallelInsert;
+
+				if (insert)
+					insert->plan_deps = bms_add_member(insert->plan_deps, 0);
 				set_upper_references(root, plan, rtoffset);
 				set_param_references(root, plan);
 			}
@@ -2123,6 +2220,15 @@ static void
 fix_expr_common(PlannerInfo *root, Node *node)
 {
 	/* We assume callers won't call us on a NULL pointer */
+	if (IsA(node, SubPlan) && root->glob->parallelInsert &&
+		root->glob->parallelModeNeeded)
+	{
+		ParallelInsertInfo *insert = root->glob->parallelInsert;
+
+		insert->plan_deps = bms_add_member(insert->plan_deps,
+										   ((SubPlan *) node)->plan_id);
+	}
+
 	if (IsA(node, Aggref))
 	{
 		record_plan_function_dependency(root,
diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c
index 1674735117c..0097428ec02 100644
--- a/src/backend/optimizer/prep/prepjointree.c
+++ b/src/backend/optimizer/prep/prepjointree.c
@@ -1301,6 +1301,11 @@ pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
 		int			varno = ((RangeTblRef *) jtnode)->rtindex;
 		RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
 
+		/* Keep the parallelizable source separate from the INSERT. */
+		if (root->glob->parallelInsert && root->query_level == 1 &&
+			varno == root->glob->parallelInsert->source_rti)
+			return jtnode;
+
 		/*
 		 * Is this a subquery RTE, and if so, is the subquery simple enough to
 		 * pull up?
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca097..d2181ffa8a8 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -955,6 +955,13 @@
   boot_val => 'true',
 },
 
+{ name => 'enable_insert_select_parallel', type => 'bool', context => 'PGC_USERSET', group => 'QUERY_TUNING_METHOD',
+  short_desc => 'Enables parallel plans for the SELECT part of INSERT ... SELECT.',
+  flags => 'GUC_EXPLAIN',
+  variable => 'enable_insert_select_parallel',
+  boot_val => 'false',
+},
+
 { name => 'enable_material', type => 'bool', context => 'PGC_USERSET', group => 'QUERY_TUNING_METHOD',
   short_desc => 'Enables the planner\'s use of materialization.',
   flags => 'GUC_EXPLAIN',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index b492b3af06c..5c53351bc44 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -436,6 +436,7 @@
 #enable_incremental_sort = on
 #enable_indexscan = on
 #enable_indexonlyscan = on
+#enable_insert_select_parallel = off
 #enable_material = on
 #enable_memoize = on
 #enable_mergejoin = on
diff --git a/src/include/optimizer/optimizer.h b/src/include/optimizer/optimizer.h
index 85550b0274e..a43983e5d3b 100644
--- a/src/include/optimizer/optimizer.h
+++ b/src/include/optimizer/optimizer.h
@@ -101,6 +101,7 @@ typedef enum
 /* GUC parameters */
 extern PGDLLIMPORT int debug_parallel_query;
 extern PGDLLIMPORT bool parallel_leader_participation;
+extern PGDLLIMPORT bool enable_insert_select_parallel;
 extern PGDLLIMPORT bool enable_distinct_reordering;
 
 extern PlannedStmt *planner(Query *parse, const char *query_string,
diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h
index c23ab568b98..a304a419f39 100644
--- a/src/include/optimizer/planmain.h
+++ b/src/include/optimizer/planmain.h
@@ -117,6 +117,7 @@ extern bool remove_useless_self_joins(PlannerInfo *root, List *joinlist);
  * prototypes for plan/setrefs.c
  */
 extern Plan *set_plan_references(PlannerInfo *root, Plan *plan);
+extern Plan *set_stmt_references(PlannerInfo *root, Plan *plan);
 extern bool trivial_subqueryscan(SubqueryScan *plan);
 extern Param *find_minmax_agg_replacement_param(PlannerInfo *root,
 												Aggref *aggref);
diff --git a/src/test/regress/expected/sysviews.out b/src/test/regress/expected/sysviews.out
index f2bb803d1d5..6207fa8ef54 100644
--- a/src/test/regress/expected/sysviews.out
+++ b/src/test/regress/expected/sysviews.out
@@ -168,6 +168,7 @@ select name, setting from pg_settings where name like 'enable%';
  enable_incremental_sort        | on
  enable_indexonlyscan           | on
  enable_indexscan               | on
+ enable_insert_select_parallel  | off
  enable_material                | on
  enable_memoize                 | on
  enable_mergejoin               | on
@@ -182,7 +183,7 @@ select name, setting from pg_settings where name like 'enable%';
  enable_seqscan                 | on
  enable_sort                    | on
  enable_tidscan                 | on
-(27 rows)
+(28 rows)
 
 -- There are always wait event descriptions for various types.  InjectionPoint
 -- may be present or absent, depending on history since last postmaster start.
diff --git a/src/test/regress/expected/write_parallel.out b/src/test/regress/expected/write_parallel.out
index dc0c4ba587e..ecbca293c56 100644
--- a/src/test/regress/expected/write_parallel.out
+++ b/src/test/regress/expected/write_parallel.out
@@ -77,4 +77,202 @@ explain (costs off) create table parallel_write as execute prep_stmt;
 
 create table parallel_write as execute prep_stmt;
 drop table parallel_write;
+create table parallel_source with (parallel_workers = 2) as
+  select i from generate_series(1, 10000) g(i);
+analyze parallel_source;
+create table parallel_write (i int primary key, s int generated by default as identity);
+-- Only buffer an INSERT source if the option is on and the plan is parallel.
+explain (costs off) insert into parallel_write (i, s) select i, i from parallel_source;
+            QUERY PLAN             
+-----------------------------------
+ Insert on parallel_write
+   ->  Seq Scan on parallel_source
+(2 rows)
+
+set enable_insert_select_parallel = on;
+explain (costs off) insert into parallel_write (i, s) select i, i from parallel_source;
+                       QUERY PLAN                       
+--------------------------------------------------------
+ Insert on parallel_write
+   ->  TupleBuffer
+         ->  Gather
+               Workers Planned: 2
+               ->  Parallel Seq Scan on parallel_source
+(5 rows)
+
+explain (costs off) insert into parallel_write (i) select 42;
+               QUERY PLAN                
+-----------------------------------------
+ Insert on parallel_write
+   ->  Subquery Scan on unnamed_subquery
+         ->  Result
+(3 rows)
+
+-- Force the buffer to spill, and check that all the rows survive.
+set work_mem = '64kB';
+do $$
+declare
+  p json;
+begin
+  execute 'explain (analyze, format json)
+           insert into parallel_write (i, s) select i, i from parallel_source' into p;
+  raise notice 'TupleBuffer storage: %, workers launched: %',
+    p #>> '{0,Plan,Plans,0,Storage}', p #>> '{0,Plan,Plans,0,Plans,0,Workers Launched}';
+end $$;
+NOTICE:  TupleBuffer storage: Disk, workers launched: 2
+select count(*), sum(i) from parallel_write;
+ count |   sum    
+-------+----------
+ 10000 | 50005000
+(1 row)
+
+-- LIMIT can leave Gather Merge workers active.  Shut them down before
+-- evaluating the identity default and performing the conflict updates.
+explain (costs off)
+insert into parallel_write (i) select i from parallel_source order by i desc limit 2
+  on conflict (i) do update set s = excluded.s returning i, s;
+                                QUERY PLAN                                
+--------------------------------------------------------------------------
+ Insert on parallel_write
+   Conflict Resolution: UPDATE
+   Conflict Arbiter Indexes: parallel_write_pkey
+   ->  Subquery Scan on unnamed_subquery
+         ->  TupleBuffer
+               ->  Limit
+                     ->  Gather Merge
+                           Workers Planned: 2
+                           ->  Sort
+                                 Sort Key: parallel_source.i DESC
+                                 ->  Parallel Seq Scan on parallel_source
+(11 rows)
+
+insert into parallel_write (i) select i from parallel_source order by i desc limit 2
+  on conflict (i) do update set s = excluded.s returning i, s;
+   i   | s 
+-------+---
+ 10000 | 1
+  9999 | 2
+(2 rows)
+
+-- A parallel initplan of the SELECT also requires a buffer.  Its LIMIT
+-- leaves workers to be shut down before evaluating the identity default.
+explain (costs off)
+insert into parallel_write (i)
+  select (select i + 1 from parallel_source order by i desc limit 1);
+                                 QUERY PLAN                                 
+----------------------------------------------------------------------------
+ Insert on parallel_write
+   ->  Subquery Scan on unnamed_subquery
+         ->  TupleBuffer
+               InitPlan expr_1
+                 ->  Limit
+                       ->  Gather Merge
+                             Workers Planned: 2
+                             ->  Sort
+                                   Sort Key: parallel_source.i DESC
+                                   ->  Parallel Seq Scan on parallel_source
+               ->  Result
+(11 rows)
+
+insert into parallel_write (i)
+  select (select i + 1 from parallel_source order by i desc limit 1) returning i, s;
+   i   | s 
+-------+---
+ 10001 | 3
+(1 row)
+
+-- A failure on the second source row must not consume an identity value for
+-- the first.  Sequence advances, unlike inserted rows, survive rollback.
+savepoint before_error;
+insert into parallel_write (i)
+  select (select max(i) + 2 from parallel_source) / n from (values (1), (0)) v(n);
+ERROR:  division by zero
+rollback to before_error;
+select currval(pg_get_serial_sequence('parallel_write', 's'));
+ currval 
+---------
+       3
+(1 row)
+
+-- A row-locking source or a data-modifying CTE still rules out parallelism.
+explain (costs off)
+insert into parallel_write (i) select i from parallel_source for update;
+                  QUERY PLAN                   
+-----------------------------------------------
+ Insert on parallel_write
+   ->  Subquery Scan on unnamed_subquery
+         ->  LockRows
+               ->  Seq Scan on parallel_source
+(4 rows)
+
+explain (costs off)
+with d as (delete from parallel_write returning i)
+insert into parallel_write (i) select i from parallel_source;
+                        QUERY PLAN                         
+-----------------------------------------------------------
+ Insert on parallel_write
+   CTE d
+     ->  Delete on parallel_write parallel_write_1
+           ->  Seq Scan on parallel_write parallel_write_1
+   ->  Seq Scan on parallel_source
+(5 rows)
+
+-- setrefs discards a parallel hashed SubPlan in favor of a serial index
+-- probe.  The TupleBuffer remains, but must pass the first row through
+-- before the second row raises an error.
+create unique index on parallel_source(i);
+create temp table parallel_outer as select i from (values (1), (2)) v(i);
+analyze parallel_outer;
+reset work_mem;
+explain (costs off)
+insert into parallel_write (i)
+  select 20000 + exists (select from parallel_source s where s.i = o.i)::int
+                 / (2 - row_number() over ())::int
+  from parallel_outer o;
+                                         QUERY PLAN                                         
+--------------------------------------------------------------------------------------------
+ Insert on parallel_write
+   ->  Subquery Scan on unnamed_subquery
+         ->  TupleBuffer
+               Buffering: false
+               ->  WindowAgg
+                     Window: w1 AS (ROWS UNBOUNDED PRECEDING)
+                     ->  Seq Scan on parallel_outer o
+                     SubPlan exists_1
+                       ->  Index Only Scan using parallel_source_i_idx on parallel_source s
+                             Index Cond: (i = o.i)
+(10 rows)
+
+savepoint before_passthrough_error;
+insert into parallel_write (i)
+  select 20000 + exists (select from parallel_source s where s.i = o.i)::int
+                 / (2 - row_number() over ())::int
+  from parallel_outer o;
+ERROR:  division by zero
+rollback to before_passthrough_error;
+select currval(pg_get_serial_sequence('parallel_write', 's'));
+ currval 
+---------
+       4
+(1 row)
+
+-- With more outer rows, the parallel hashed SubPlan wins and needs buffering
+-- even though the outer scan is serial.
+insert into parallel_outer select generate_series(3, 1000);
+analyze parallel_outer;
+explain (costs off)
+insert into parallel_write (i, s)
+  select o.i + 20000, exists (select from parallel_source s where s.i = o.i)::int
+  from parallel_outer o;
+                            QUERY PLAN                            
+------------------------------------------------------------------
+ Insert on parallel_write
+   ->  TupleBuffer
+         ->  Seq Scan on parallel_outer o
+               SubPlan exists_to_any_1
+                 ->  Gather
+                       Workers Planned: 2
+                       ->  Parallel Seq Scan on parallel_source s
+(7 rows)
+
 rollback;
diff --git a/src/test/regress/sql/write_parallel.sql b/src/test/regress/sql/write_parallel.sql
index ae660dc2265..e05e14358dd 100644
--- a/src/test/regress/sql/write_parallel.sql
+++ b/src/test/regress/sql/write_parallel.sql
@@ -40,4 +40,88 @@ explain (costs off) create table parallel_write as execute prep_stmt;
 create table parallel_write as execute prep_stmt;
 drop table parallel_write;
 
+create table parallel_source with (parallel_workers = 2) as
+  select i from generate_series(1, 10000) g(i);
+analyze parallel_source;
+create table parallel_write (i int primary key, s int generated by default as identity);
+
+-- Only buffer an INSERT source if the option is on and the plan is parallel.
+explain (costs off) insert into parallel_write (i, s) select i, i from parallel_source;
+set enable_insert_select_parallel = on;
+explain (costs off) insert into parallel_write (i, s) select i, i from parallel_source;
+explain (costs off) insert into parallel_write (i) select 42;
+
+-- Force the buffer to spill, and check that all the rows survive.
+set work_mem = '64kB';
+do $$
+declare
+  p json;
+begin
+  execute 'explain (analyze, format json)
+           insert into parallel_write (i, s) select i, i from parallel_source' into p;
+  raise notice 'TupleBuffer storage: %, workers launched: %',
+    p #>> '{0,Plan,Plans,0,Storage}', p #>> '{0,Plan,Plans,0,Plans,0,Workers Launched}';
+end $$;
+select count(*), sum(i) from parallel_write;
+
+-- LIMIT can leave Gather Merge workers active.  Shut them down before
+-- evaluating the identity default and performing the conflict updates.
+explain (costs off)
+insert into parallel_write (i) select i from parallel_source order by i desc limit 2
+  on conflict (i) do update set s = excluded.s returning i, s;
+insert into parallel_write (i) select i from parallel_source order by i desc limit 2
+  on conflict (i) do update set s = excluded.s returning i, s;
+
+-- A parallel initplan of the SELECT also requires a buffer.  Its LIMIT
+-- leaves workers to be shut down before evaluating the identity default.
+explain (costs off)
+insert into parallel_write (i)
+  select (select i + 1 from parallel_source order by i desc limit 1);
+insert into parallel_write (i)
+  select (select i + 1 from parallel_source order by i desc limit 1) returning i, s;
+
+-- A failure on the second source row must not consume an identity value for
+-- the first.  Sequence advances, unlike inserted rows, survive rollback.
+savepoint before_error;
+insert into parallel_write (i)
+  select (select max(i) + 2 from parallel_source) / n from (values (1), (0)) v(n);
+rollback to before_error;
+select currval(pg_get_serial_sequence('parallel_write', 's'));
+
+-- A row-locking source or a data-modifying CTE still rules out parallelism.
+explain (costs off)
+insert into parallel_write (i) select i from parallel_source for update;
+explain (costs off)
+with d as (delete from parallel_write returning i)
+insert into parallel_write (i) select i from parallel_source;
+
+-- setrefs discards a parallel hashed SubPlan in favor of a serial index
+-- probe.  The TupleBuffer remains, but must pass the first row through
+-- before the second row raises an error.
+create unique index on parallel_source(i);
+create temp table parallel_outer as select i from (values (1), (2)) v(i);
+analyze parallel_outer;
+reset work_mem;
+explain (costs off)
+insert into parallel_write (i)
+  select 20000 + exists (select from parallel_source s where s.i = o.i)::int
+                 / (2 - row_number() over ())::int
+  from parallel_outer o;
+savepoint before_passthrough_error;
+insert into parallel_write (i)
+  select 20000 + exists (select from parallel_source s where s.i = o.i)::int
+                 / (2 - row_number() over ())::int
+  from parallel_outer o;
+rollback to before_passthrough_error;
+select currval(pg_get_serial_sequence('parallel_write', 's'));
+
+-- With more outer rows, the parallel hashed SubPlan wins and needs buffering
+-- even though the outer scan is serial.
+insert into parallel_outer select generate_series(3, 1000);
+analyze parallel_outer;
+explain (costs off)
+insert into parallel_write (i, s)
+  select o.i + 20000, exists (select from parallel_source s where s.i = o.i)::int
+  from parallel_outer o;
+
 rollback;
-- 
2.56.1

