Hi,

For comparison, here's an early PoC of the buffering idea. I've realized
we kinda already have this buffering capability - Materialize spills
tuples to tuplestore (but not eagerly). Having an executor node seems
like a convenient approach, because it then can be part of the regular
query planning etc. So I gave that a try.

0001 introduces a new TupleBuffer node (path + plan), mimicking what
Materialize does, but accumulating tuples eagerly (more like Sort), and
also taking over the parallel mode setup (instead of ExecutePlan). But
it's just an infrastructure (planner/executor/explain), the node is not
used anywhere yet.

0002 integrates the node into INSERT ... SELECT queries. With it enabled
(the GUC is "off" by default) a plan changes from

                   QUERY PLAN
    -----------------------------------------
     Insert on t
       ->  Subquery Scan on unnamed_subquery
             ->  HashAggregate
                   Group Key: s.a
                   ->  Seq Scan on s
    (5 rows)

to

                                QUERY PLAN
    ------------------------------------------------------------------
     Insert on t
       ->  Subquery Scan on unnamed_subquery
             ->  TupleBuffer
                   ->  Finalize GroupAggregate
                         Group Key: s.a
                         ->  Gather Merge
                               Workers Planned: 2
                               ->  Sort
                                     Sort Key: s.a
                                     ->  Partial HashAggregate
                                           Group Key: s.a
                                           ->  Parallel Seq Scan on s
    (12 rows)

In EXPLAIN ANALYZE it prints more info (how much disk space etc.).


I think this works pretty well, but there are some problems to solve.
The main problem is that during planning we don't know for sure if the
plan actually is parallel. We can know for the "main" plan, but if there
are alternative subplans, then we don't know until after setrefs. The
actual plan gets selected by fix_alternative_subplan(). So we don't even
know for sure in create_plan().

The PoC deals with that by switching the buffer to "passthrough" mode
when the ultimate plan happens to be serial, i.e. the tuples are
returned immediately, without writing it to the tuplestore.

Maybe it's be simpler with a tuplestore integrated into the ModifyTable
node, not sure yet. It's also possible I missed something, and there's a
simpler way to handle this.

Another thing I'm not very happy with is the es_parallel_insert_select
flag, and root->glob->parallelInsert. It seems a bit cumbersome to me,
but I haven't found a better solution yet.

One thing that occurred to me is that the TupleBuffer might be useful
more widely. There are places where we disallow parallel query because
the execution might get suspended (say, when a client uses cursors,
which some libraries do automatically). If the client consumes just a
tiny fraction of tuples, that makes perfect sense. But if the client
consumes all tuples, maybe it'd be better to add TupleBuffer on top, and
then use parallel execution. Just a wild idea, though.


regards

-- 
Tomas Vondra
From 7796fdcd56a87c05c400108e9a66c97754f64800 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 24 Nov 2026 11:16:25 -0500
Subject: [PATCH v1-PoC-buffer 1/2] Add TupleBuffer, an eager materialization
 plan node

Unlike Material, an eager TupleBuffer consumes its entire input before
returning its first row.  Give it its own path, plan, and executor
state, including positioning, rescan, costing, and EXPLAIN support.

Provide a conditional buffer for callers that must finish a parallel
read before returning rows.  It can shut down workers after the fill, or
pass tuples through without a tuplestore if the final plan is serial.
No query selects this path yet.
---
 src/backend/commands/explain.c          |  27 ++++
 src/backend/executor/Makefile           |   1 +
 src/backend/executor/execAmi.c          |  33 +++++
 src/backend/executor/execProcnode.c     |  10 ++
 src/backend/executor/execUtils.c        |   1 +
 src/backend/executor/meson.build        |   1 +
 src/backend/executor/nodeTupleBuffer.c  | 185 ++++++++++++++++++++++++
 src/backend/optimizer/README            |   1 +
 src/backend/optimizer/path/costsize.c   |  30 ++++
 src/backend/optimizer/plan/createplan.c |  59 ++++++++
 src/backend/optimizer/plan/setrefs.c    |   1 +
 src/backend/optimizer/plan/subselect.c  |   1 +
 src/backend/optimizer/util/pathnode.c   |  67 +++++++++
 src/backend/optimizer/util/relnode.c    |   2 +
 src/include/executor/nodeTupleBuffer.h  |  24 +++
 src/include/nodes/execnodes.h           |  14 ++
 src/include/nodes/pathnodes.h           |  31 ++++
 src/include/nodes/plannodes.h           |  13 ++
 src/include/optimizer/cost.h            |   2 +
 src/include/optimizer/pathnode.h        |   2 +
 src/tools/pgindent/typedefs.list        |   5 +
 21 files changed, 510 insertions(+)
 create mode 100644 src/backend/executor/nodeTupleBuffer.c
 create mode 100644 src/include/executor/nodeTupleBuffer.h

diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c
index f778075b9eb..e568a736402 100644
--- a/src/backend/commands/explain.c
+++ b/src/backend/commands/explain.c
@@ -128,6 +128,7 @@ static void show_incremental_sort_info(IncrementalSortState *incrsortstate,
 									   ExplainState *es);
 static void show_hash_info(HashState *hashstate, ExplainState *es);
 static void show_material_info(MaterialState *mstate, ExplainState *es);
+static void show_tuplebuffer_info(TupleBufferState *bstate, ExplainState *es);
 static void show_windowagg_info(WindowAggState *winstate, ExplainState *es);
 static void show_ctescan_info(CteScanState *ctescanstate, ExplainState *es);
 static void show_functionscan_info(FunctionScanState *fsstate,
@@ -1530,6 +1531,9 @@ ExplainNode(PlanState *planstate, List *ancestors,
 		case T_Material:
 			pname = sname = "Materialize";
 			break;
+		case T_TupleBuffer:
+			pname = sname = "TupleBuffer";
+			break;
 		case T_Memoize:
 			pname = sname = "Memoize";
 			break;
@@ -2266,6 +2270,9 @@ ExplainNode(PlanState *planstate, List *ancestors,
 		case T_Material:
 			show_material_info(castNode(MaterialState, planstate), es);
 			break;
+		case T_TupleBuffer:
+			show_tuplebuffer_info(castNode(TupleBufferState, planstate), es);
+			break;
 		case T_Memoize:
 			show_memoize_info(castNode(MemoizeState, planstate), ancestors,
 							  es);
@@ -3531,6 +3538,26 @@ show_material_info(MaterialState *mstate, ExplainState *es)
 	}
 }
 
+/* Show whether rows are buffered and, if so, peak tuplestore usage. */
+static void
+show_tuplebuffer_info(TupleBufferState *bstate, ExplainState *es)
+{
+	TupleBuffer *plan = castNode(TupleBuffer, bstate->ps.plan);
+	bool		buffering = plan->mode != TUPLEBUFFER_PASSTHROUGH;
+
+	if (!buffering || es->format != EXPLAIN_FORMAT_TEXT)
+		ExplainPropertyBool("Buffering", buffering, es);
+
+	if (es->analyze && bstate->tuplestore != NULL)
+	{
+		bool		usedDisk;
+		int64		maxSpaceUsed;
+
+		tuplestore_get_stats(bstate->tuplestore, &usedDisk, &maxSpaceUsed);
+		show_storage_info(usedDisk, maxSpaceUsed, es);
+	}
+}
+
 /*
  * Show information on WindowAgg node, storage method and maximum memory/disk
  * space used.
diff --git a/src/backend/executor/Makefile b/src/backend/executor/Makefile
index 11118d0ce02..3f82b7db72d 100644
--- a/src/backend/executor/Makefile
+++ b/src/backend/executor/Makefile
@@ -71,6 +71,7 @@ OBJS = \
 	nodeTableFuncscan.o \
 	nodeTidrangescan.o \
 	nodeTidscan.o \
+	nodeTupleBuffer.o \
 	nodeUnique.o \
 	nodeValuesscan.o \
 	nodeWindowAgg.o \
diff --git a/src/backend/executor/execAmi.c b/src/backend/executor/execAmi.c
index 41f9bce70a7..29b0e4feaa5 100644
--- a/src/backend/executor/execAmi.c
+++ b/src/backend/executor/execAmi.c
@@ -56,6 +56,7 @@
 #include "executor/nodeTableFuncscan.h"
 #include "executor/nodeTidrangescan.h"
 #include "executor/nodeTidscan.h"
+#include "executor/nodeTupleBuffer.h"
 #include "executor/nodeUnique.h"
 #include "executor/nodeValuesscan.h"
 #include "executor/nodeWindowAgg.h"
@@ -262,6 +263,10 @@ ExecReScan(PlanState *node)
 			ExecReScanMaterial((MaterialState *) node);
 			break;
 
+		case T_TupleBufferState:
+			ExecReScanTupleBuffer((TupleBufferState *) node);
+			break;
+
 		case T_MemoizeState:
 			ExecReScanMemoize((MemoizeState *) node);
 			break;
@@ -352,6 +357,10 @@ ExecMarkPos(PlanState *node)
 			ExecMaterialMarkPos((MaterialState *) node);
 			break;
 
+		case T_TupleBufferState:
+			ExecTupleBufferMarkPos((TupleBufferState *) node);
+			break;
+
 		case T_SortState:
 			ExecSortMarkPos((SortState *) node);
 			break;
@@ -401,6 +410,10 @@ ExecRestrPos(PlanState *node)
 			ExecMaterialRestrPos((MaterialState *) node);
 			break;
 
+		case T_TupleBufferState:
+			ExecTupleBufferRestrPos((TupleBufferState *) node);
+			break;
+
 		case T_SortState:
 			ExecSortRestrPos((SortState *) node);
 			break;
@@ -440,6 +453,18 @@ ExecSupportsMarkRestore(Path *pathnode)
 			 */
 			return castNode(IndexPath, pathnode)->indexinfo->amcanmarkpos;
 
+		case T_TupleBuffer:
+			{
+				TupleBufferPath *bpath = castNode(TupleBufferPath, pathnode);
+
+				/*
+				 * The final mode isn't known at path costing time.  If the
+				 * buffer passes through, only its child can mark and restore.
+				 */
+				return !bpath->buffer_if_parallel ||
+					ExecSupportsMarkRestore(bpath->subpath);
+			}
+
 		case T_Material:
 		case T_Sort:
 			return true;
@@ -570,6 +595,10 @@ ExecSupportsBackwardScan(Plan *node)
 		case T_SubqueryScan:
 			return ExecSupportsBackwardScan(((SubqueryScan *) node)->subplan);
 
+		case T_TupleBuffer:
+			return ((TupleBuffer *) node)->mode != TUPLEBUFFER_PASSTHROUGH ||
+				ExecSupportsBackwardScan(outerPlan(node));
+
 		case T_CustomScan:
 			if (((CustomScan *) node)->flags & CUSTOMPATH_SUPPORT_BACKWARD_SCAN)
 				return true;
@@ -653,6 +682,10 @@ ExecMaterializesOutput(NodeTag plantype)
 		case T_Sort:
 			return true;
 
+		case T_TupleBuffer:
+			/* The node tag alone can't rule out pass-through mode. */
+			return false;
+
 		default:
 			break;
 	}
diff --git a/src/backend/executor/execProcnode.c b/src/backend/executor/execProcnode.c
index 7c4c66e323f..abefcc4d3f0 100644
--- a/src/backend/executor/execProcnode.c
+++ b/src/backend/executor/execProcnode.c
@@ -113,6 +113,7 @@
 #include "executor/nodeTableFuncscan.h"
 #include "executor/nodeTidrangescan.h"
 #include "executor/nodeTidscan.h"
+#include "executor/nodeTupleBuffer.h"
 #include "executor/nodeUnique.h"
 #include "executor/nodeValuesscan.h"
 #include "executor/nodeWindowAgg.h"
@@ -317,6 +318,11 @@ ExecInitNode(Plan *node, EState *estate, int eflags)
 													estate, eflags);
 			break;
 
+		case T_TupleBuffer:
+			result = (PlanState *) ExecInitTupleBuffer((TupleBuffer *) node,
+													   estate, eflags);
+			break;
+
 		case T_Sort:
 			result = (PlanState *) ExecInitSort((Sort *) node,
 												estate, eflags);
@@ -687,6 +693,10 @@ ExecEndNode(PlanState *node)
 			ExecEndMaterial((MaterialState *) node);
 			break;
 
+		case T_TupleBufferState:
+			ExecEndTupleBuffer((TupleBufferState *) node);
+			break;
+
 		case T_SortState:
 			ExecEndSort((SortState *) node);
 			break;
diff --git a/src/backend/executor/execUtils.c b/src/backend/executor/execUtils.c
index c0c4276acbf..fe32ed36621 100644
--- a/src/backend/executor/execUtils.c
+++ b/src/backend/executor/execUtils.c
@@ -164,6 +164,7 @@ CreateExecutorState(void)
 	estate->es_sourceText = NULL;
 
 	estate->es_use_parallel_mode = false;
+	estate->es_parallel_insert_select = false;
 	estate->es_parallel_workers_to_launch = 0;
 	estate->es_parallel_workers_launched = 0;
 
diff --git a/src/backend/executor/meson.build b/src/backend/executor/meson.build
index dc45be0b2ce..c5a79cfcdc4 100644
--- a/src/backend/executor/meson.build
+++ b/src/backend/executor/meson.build
@@ -59,6 +59,7 @@ backend_sources += files(
   'nodeTableFuncscan.c',
   'nodeTidrangescan.c',
   'nodeTidscan.c',
+  'nodeTupleBuffer.c',
   'nodeUnique.c',
   'nodeValuesscan.c',
   'nodeWindowAgg.c',
diff --git a/src/backend/executor/nodeTupleBuffer.c b/src/backend/executor/nodeTupleBuffer.c
new file mode 100644
index 00000000000..67f497c030e
--- /dev/null
+++ b/src/backend/executor/nodeTupleBuffer.c
@@ -0,0 +1,185 @@
+/*-------------------------------------------------------------------------
+ *
+ * nodeTupleBuffer.c
+ *	  Buffer a subplan to completion before returning its first tuple.
+ *
+ * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	  src/backend/executor/nodeTupleBuffer.c
+ *
+ *-------------------------------------------------------------------------
+ */
+#include "postgres.h"
+
+#include "access/xact.h"
+#include "executor/executor.h"
+#include "executor/nodeTupleBuffer.h"
+#include "miscadmin.h"
+#include "utils/tuplestore.h"
+
+static TupleTableSlot *
+ExecTupleBuffer(PlanState *pstate)
+{
+	TupleBufferState *node = castNode(TupleBufferState, pstate);
+	EState	   *estate = pstate->state;
+	ScanDirection dir = estate->es_direction;
+	TupleTableSlot *slot = pstate->ps_ResultTupleSlot;
+
+	CHECK_FOR_INTERRUPTS();
+
+	if (!node->filled)
+	{
+		PlanState  *outer = outerPlanState(node);
+		bool		enter_parallel_mode = estate->es_parallel_insert_select &&
+			castNode(TupleBuffer, pstate->plan)->mode == TUPLEBUFFER_PARALLEL;
+		TupleTableSlot *input;
+
+		if (node->tuplestore == NULL)
+		{
+			node->tuplestore = tuplestore_begin_heap(true, false, work_mem);
+			tuplestore_set_eflags(node->tuplestore, node->eflags);
+			if (node->eflags & EXEC_FLAG_MARK)
+				node->markptr = tuplestore_alloc_read_pointer(node->tuplestore,
+															  node->eflags);
+		}
+
+		if (enter_parallel_mode)
+		{
+			EnterParallelMode();
+			estate->es_use_parallel_mode = true;
+		}
+
+		estate->es_direction = ForwardScanDirection;
+		for (;;)
+		{
+			input = ExecProcNode(outer);
+			if (TupIsNull(input))
+				break;
+			tuplestore_puttupleslot(node->tuplestore, input);
+		}
+		if (enter_parallel_mode)
+		{
+			/*
+			 * EOF need not have exhausted a Gather below a Limit, including
+			 * one in an initplan attached to the buffer itself.  Stop all
+			 * such workers before allowing the first write.
+			 */
+			ExecShutdownNode(outer);
+			foreach_node(SubPlanState, sstate, pstate->initPlan)
+				ExecShutdownNode(sstate->planstate);
+			estate->es_use_parallel_mode = false;
+			ExitParallelMode();
+		}
+		estate->es_direction = dir;
+		node->filled = true;
+	}
+
+	tuplestore_gettupleslot(node->tuplestore, ScanDirectionIsForward(dir),
+							false, slot);
+	return slot;
+}
+
+static TupleTableSlot *
+ExecTupleBufferPassthrough(PlanState *pstate)
+{
+	CHECK_FOR_INTERRUPTS();
+	return ExecProcNode(outerPlanState(pstate));
+}
+
+TupleBufferState *
+ExecInitTupleBuffer(TupleBuffer *plan, EState *estate, int eflags)
+{
+	TupleBufferState *node = makeNode(TupleBufferState);
+
+	node->ps.plan = (Plan *) plan;
+	node->ps.state = estate;
+
+	node->eflags = eflags & (EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD |
+							 EXEC_FLAG_MARK);
+	if (plan->mode == TUPLEBUFFER_PASSTHROUGH)
+	{
+		/* The child supplies the slot and handles all positioning requests. */
+		node->ps.ExecProcNode = ExecTupleBufferPassthrough;
+		outerPlanState(node) = ExecInitNode(outerPlan(plan), estate, eflags);
+		ExecInitResultTypeTL(&node->ps);
+		node->ps.resultops = ExecGetResultSlotOps(outerPlanState(node),
+												  &node->ps.resultopsfixed);
+		node->ps.resultopsset = true;
+		return node;
+	}
+
+	node->ps.ExecProcNode = ExecTupleBuffer;
+	/* A backwards scan must be able to reach the start of the buffer. */
+	if (eflags & EXEC_FLAG_BACKWARD)
+		node->eflags |= EXEC_FLAG_REWIND;
+
+	/* The child is only ever scanned forwards. */
+	outerPlanState(node) = ExecInitNode(outerPlan(plan), estate,
+										eflags & ~node->eflags);
+	ExecInitResultTupleSlotTL(&node->ps, &TTSOpsMinimalTuple);
+
+	return node;
+}
+
+void
+ExecReScanTupleBuffer(TupleBufferState *node)
+{
+	PlanState  *outer = outerPlanState(node);
+
+	if (castNode(TupleBuffer, node->ps.plan)->mode == TUPLEBUFFER_PASSTHROUGH)
+	{
+		if (outer->chgParam == NULL)
+			ExecReScan(outer);
+		return;
+	}
+
+	ExecClearTuple(node->ps.ps_ResultTupleSlot);
+	if (node->tuplestore == NULL)
+		return;
+
+	if (outer->chgParam == NULL && (node->eflags & EXEC_FLAG_REWIND))
+		tuplestore_rescan(node->tuplestore);
+	else
+	{
+		/* Keep the store's peak usage across fills for EXPLAIN ANALYZE. */
+		tuplestore_clear(node->tuplestore);
+		node->filled = false;
+		if (outer->chgParam == NULL)
+			ExecReScan(outer);
+	}
+}
+
+void
+ExecTupleBufferMarkPos(TupleBufferState *node)
+{
+	Assert(node->eflags & EXEC_FLAG_MARK);
+	if (castNode(TupleBuffer, node->ps.plan)->mode == TUPLEBUFFER_PASSTHROUGH)
+		ExecMarkPos(outerPlanState(node));
+	else if (node->tuplestore != NULL)
+	{
+		tuplestore_copy_read_pointer(node->tuplestore, 0, node->markptr);
+		tuplestore_trim(node->tuplestore);
+	}
+}
+
+void
+ExecTupleBufferRestrPos(TupleBufferState *node)
+{
+	Assert(node->eflags & EXEC_FLAG_MARK);
+	if (castNode(TupleBuffer, node->ps.plan)->mode == TUPLEBUFFER_PASSTHROUGH)
+		ExecRestrPos(outerPlanState(node));
+	else if (node->tuplestore != NULL)
+		tuplestore_copy_read_pointer(node->tuplestore, node->markptr, 0);
+}
+
+void
+ExecEndTupleBuffer(TupleBufferState *node)
+{
+	if (node->tuplestore != NULL)
+	{
+		tuplestore_end(node->tuplestore);
+		node->tuplestore = NULL;
+	}
+	ExecEndNode(outerPlanState(node));
+}
diff --git a/src/backend/optimizer/README b/src/backend/optimizer/README
index 73d0b7536ac..93704e5e706 100644
--- a/src/backend/optimizer/README
+++ b/src/backend/optimizer/README
@@ -639,6 +639,7 @@ RelOptInfo      - a relation or joined relations
   MergeAppendPath - merge multiple subpaths, preserving their common sort order
   GroupResultPath - childless Result plan node (used for degenerate grouping)
   MaterialPath  - a Material plan node
+  TupleBufferPath - buffer an entire subpath before returning its first tuple
   MemoizePath   - a Memoize plan node for caching tuples from sub-paths
   GatherPath    - collect the results of parallel workers
   GatherMergePath - collect parallel results, preserving their common sort order
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index f760ef9aa3a..01011a7b7dc 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -2635,6 +2635,31 @@ cost_material(Path *path,
 	path->total_cost = startup_cost + run_cost;
 }
 
+/*
+ * cost_tuplebuffer
+ *	  Charge the entire input and the cost of storing it to startup.
+ *	  The first scan and subsequent scans just read the buffered tuples.
+ */
+void
+cost_tuplebuffer(Cost *startup_cost, Cost *total_cost, Cost input_total_cost,
+				 double tuples, int width)
+{
+	double		nbytes = relation_byte_size(tuples, width);
+	Cost		fill_cost = 2 * cpu_operator_cost * tuples;
+	Cost		run_cost = cpu_operator_cost * tuples;
+
+	if (nbytes > work_mem * (Size) 1024)
+	{
+		Cost		spill_cost = seq_page_cost * ceil(nbytes / BLCKSZ);
+
+		fill_cost += spill_cost;
+		run_cost += spill_cost;
+	}
+
+	*startup_cost = input_total_cost + fill_cost;
+	*total_cost = *startup_cost + run_cost;
+}
+
 /*
  * cost_memoize_rescan
  *	  Determines the estimated cost of rescanning a Memoize node.
@@ -4887,6 +4912,11 @@ cost_rescan(PlannerInfo *root, Path *path,
 {
 	switch (path->pathtype)
 	{
+		case T_TupleBuffer:
+			/* Only the cost of reading the completed buffer recurs. */
+			*rescan_startup_cost = 0;
+			*rescan_total_cost = path->total_cost - path->startup_cost;
+			break;
 		case T_FunctionScan:
 
 			/*
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index bc991d31254..196d24f7a4f 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -92,6 +92,8 @@ static Result *create_group_result_plan(PlannerInfo *root,
 static ProjectSet *create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path);
 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path,
 									  int flags);
+static Plan *create_tuplebuffer_plan(PlannerInfo *root,
+									 TupleBufferPath *best_path, int flags);
 static Memoize *create_memoize_plan(PlannerInfo *root, MemoizePath *best_path,
 									int flags);
 static Gather *create_gather_plan(PlannerInfo *root, GatherPath *best_path);
@@ -473,6 +475,10 @@ create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
 												 (MaterialPath *) best_path,
 												 flags);
 			break;
+		case T_TupleBuffer:
+			plan = create_tuplebuffer_plan(root, (TupleBufferPath *) best_path,
+										   flags);
+			break;
 		case T_Memoize:
 			plan = (Plan *) create_memoize_plan(root,
 												(MemoizePath *) best_path,
@@ -1737,6 +1743,57 @@ create_material_plan(PlannerInfo *root, MaterialPath *best_path, int flags)
 	return plan;
 }
 
+/*
+ * create_tuplebuffer_plan
+ *	  Create a TupleBuffer plan over the input to be buffered.
+ */
+static Plan *
+create_tuplebuffer_plan(PlannerInfo *root, TupleBufferPath *best_path, int flags)
+{
+	TupleBuffer *plan;
+	Plan	   *subplan;
+
+	/* Store only the columns the parent needs. */
+	subplan = create_plan_recurse(root, best_path->subpath,
+								  flags | CP_SMALL_TLIST);
+
+	/*
+	 * At this point parallelModeNeeded accounts for Gathers in the source
+	 * plan as well as in its initplans and subplans.  Don't add an INSERT
+	 * buffer unless one was built.  It could still belong to a discarded
+	 * AlternativeSubPlan; setrefs will decide whether to buffer any rows.
+	 */
+	if (best_path->buffer_if_parallel && !root->glob->parallelModeNeeded)
+		return subplan;
+
+	plan = makeNode(TupleBuffer);
+	plan->plan.lefttree = subplan;
+	plan->plan.targetlist = subplan->targetlist;
+	if (best_path->buffer_if_parallel)
+	{
+		Cost		initplan_cost;
+		bool		unsafe_initplans;
+
+		plan->mode = TUPLEBUFFER_PARALLEL;
+		root->glob->parallelInsert->buffer = plan;
+
+		/*
+		 * create_plan() will attach the source's initplans to this new top
+		 * node.  Both paths already include their cost; remove it from the
+		 * child, where the initplans will no longer appear.
+		 */
+		SS_compute_initplan_cost(root->init_plans,
+								 &initplan_cost, &unsafe_initplans);
+		subplan->startup_cost -= initplan_cost;
+		subplan->total_cost -= initplan_cost;
+	}
+	else
+		plan->mode = TUPLEBUFFER_EAGER;
+	copy_generic_path_info(&plan->plan, (Path *) best_path);
+
+	return &plan->plan;
+}
+
 /*
  * create_memoize_plan
  *	  Create a Memoize plan for 'best_path' and (recursively) plans for its
@@ -7372,6 +7429,7 @@ is_projection_capable_path(Path *path)
 	{
 		case T_Hash:
 		case T_Material:
+		case T_TupleBuffer:
 		case T_Memoize:
 		case T_Sort:
 		case T_IncrementalSort:
@@ -7422,6 +7480,7 @@ is_projection_capable_plan(Plan *plan)
 	{
 		case T_Hash:
 		case T_Material:
+		case T_TupleBuffer:
 		case T_Memoize:
 		case T_Sort:
 		case T_Unique:
diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c
index 7a04de86879..9257b54a215 100644
--- a/src/backend/optimizer/plan/setrefs.c
+++ b/src/backend/optimizer/plan/setrefs.c
@@ -909,6 +909,7 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
 			}
 
 		case T_Material:
+		case T_TupleBuffer:
 		case T_Sort:
 		case T_IncrementalSort:
 		case T_Unique:
diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c
index 61f90b0c309..05278e95a63 100644
--- a/src/backend/optimizer/plan/subselect.c
+++ b/src/backend/optimizer/plan/subselect.c
@@ -3183,6 +3183,7 @@ finalize_plan(PlannerInfo *root, Plan *plan,
 
 		case T_ProjectSet:
 		case T_Material:
+		case T_TupleBuffer:
 		case T_Sort:
 		case T_IncrementalSort:
 		case T_Unique:
diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c
index 5f28174a5fa..8b0acb7a81a 100644
--- a/src/backend/optimizer/util/pathnode.c
+++ b/src/backend/optimizer/util/pathnode.c
@@ -1764,6 +1764,44 @@ create_material_path(RelOptInfo *rel, Path *subpath, bool enabled)
 	return pathnode;
 }
 
+/*
+ * create_tuplebuffer_path
+ *	  Creates a path that buffers the subpath to completion.
+ */
+TupleBufferPath *
+create_tuplebuffer_path(RelOptInfo *rel, Path *subpath, bool buffer_if_parallel)
+{
+	TupleBufferPath *pathnode = makeNode(TupleBufferPath);
+
+	Assert(subpath->parent == rel);
+
+	pathnode->path.pathtype = T_TupleBuffer;
+	pathnode->path.parent = rel;
+	pathnode->path.pathtarget = subpath->pathtarget;
+	pathnode->path.param_info = get_wrapper_parampathinfo(subpath);
+	/* The leader owns the buffer; the subpath can still contain a Gather. */
+	pathnode->path.parallel_aware = false;
+	pathnode->path.parallel_safe = false;
+	pathnode->path.parallel_workers = 0;
+	pathnode->path.pathkeys = subpath->pathkeys;
+	pathnode->subpath = subpath;
+	pathnode->buffer_if_parallel = buffer_if_parallel;
+
+	pathnode->path.rows = subpath->rows;
+	pathnode->path.disabled_nodes = subpath->disabled_nodes;
+	if (buffer_if_parallel)
+	{
+		/* Charge the INSERT for buffering only if its final plan needs it. */
+		pathnode->path.startup_cost = subpath->startup_cost;
+		pathnode->path.total_cost = subpath->total_cost;
+	}
+	else
+		cost_tuplebuffer(&pathnode->path.startup_cost, &pathnode->path.total_cost,
+						 subpath->total_cost, subpath->rows, subpath->pathtarget->width);
+
+	return pathnode;
+}
+
 /*
  * create_memoize_path
  *	  Creates a path corresponding to a Memoize plan, returning the pathnode.
@@ -4081,6 +4119,18 @@ reparameterize_path(PlannerInfo *root, Path *path,
 					(mpath->path.disabled_nodes <= spath->disabled_nodes);
 				return (Path *) create_material_path(rel, spath, enabled);
 			}
+		case T_TupleBuffer:
+			{
+				TupleBufferPath *bpath = (TupleBufferPath *) path;
+				Path	   *spath;
+
+				spath = reparameterize_path(root, bpath->subpath,
+											required_outer, loop_count);
+				if (spath == NULL)
+					return NULL;
+				return (Path *) create_tuplebuffer_path(rel, spath,
+														bpath->buffer_if_parallel);
+			}
 		case T_Memoize:
 			{
 				MemoizePath *mpath = (MemoizePath *) path;
@@ -4335,6 +4385,15 @@ do { \
 			}
 			break;
 
+		case T_TupleBufferPath:
+			{
+				TupleBufferPath *bpath = (TupleBufferPath *) path;
+
+				REPARAMETERIZE_CHILD_PATH(bpath->subpath);
+				new_path = (Path *) bpath;
+			}
+			break;
+
 		case T_MemoizePath:
 			{
 				MemoizePath *mpath = (MemoizePath *) path;
@@ -4526,6 +4585,14 @@ do { \
 			}
 			break;
 
+		case T_TupleBufferPath:
+			{
+				TupleBufferPath *bpath = (TupleBufferPath *) path;
+
+				REJECT_IF_PATH_NOT_REPARAMETERIZABLE(bpath->subpath);
+			}
+			break;
+
 		case T_MemoizePath:
 			{
 				MemoizePath *mpath = (MemoizePath *) path;
diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c
index 90a687c32da..c8c832fc08b 100644
--- a/src/backend/optimizer/util/relnode.c
+++ b/src/backend/optimizer/util/relnode.c
@@ -2293,6 +2293,8 @@ get_param_path_clause_serials(Path *path)
 			 */
 		case T_MaterialPath:
 			return get_param_path_clause_serials(((MaterialPath *) path)->subpath);
+		case T_TupleBufferPath:
+			return get_param_path_clause_serials(((TupleBufferPath *) path)->subpath);
 		case T_MemoizePath:
 			return get_param_path_clause_serials(((MemoizePath *) path)->subpath);
 		case T_ProjectionPath:
diff --git a/src/include/executor/nodeTupleBuffer.h b/src/include/executor/nodeTupleBuffer.h
new file mode 100644
index 00000000000..855de0b317f
--- /dev/null
+++ b/src/include/executor/nodeTupleBuffer.h
@@ -0,0 +1,24 @@
+/*-------------------------------------------------------------------------
+ *
+ * nodeTupleBuffer.h
+ *	  Executor support for eager tuple buffering.
+ *
+ * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
+ *
+ * src/include/executor/nodeTupleBuffer.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef NODETUPLEBUFFER_H
+#define NODETUPLEBUFFER_H
+
+#include "nodes/execnodes.h"
+
+extern TupleBufferState *ExecInitTupleBuffer(TupleBuffer *node, EState *estate,
+											 int eflags);
+extern void ExecEndTupleBuffer(TupleBufferState *node);
+extern void ExecReScanTupleBuffer(TupleBufferState *node);
+extern void ExecTupleBufferMarkPos(TupleBufferState *node);
+extern void ExecTupleBufferRestrPos(TupleBufferState *node);
+
+#endif							/* NODETUPLEBUFFER_H */
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index e4fd53c383b..91168d009e2 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -756,6 +756,7 @@ typedef struct EState
 	struct EPQState *es_epq_active;
 
 	bool		es_use_parallel_mode;	/* can we use parallel workers? */
+	bool		es_parallel_insert_select;	/* only while filling TupleBuffer */
 
 	int			es_parallel_workers_to_launch;	/* number of workers to
 												 * launch. */
@@ -2285,6 +2286,19 @@ typedef struct MaterialState
 	SharedMaterialInfo *shared_info;	/* statistics for parallel workers */
 } MaterialState;
 
+/*
+ * TupleBufferState fills the store before returning tuples, or delegates
+ * directly to the child in pass-through mode.
+ */
+typedef struct TupleBufferState
+{
+	PlanState	ps;
+	Tuplestorestate *tuplestore;
+	int			eflags;			/* tuplestore positioning capabilities */
+	int			markptr;		/* read pointer for mark/restore, if requested */
+	bool		filled;
+} TupleBufferState;
+
 struct MemoizeEntry;
 struct MemoizeKey;
 
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 2ba1dbfb67f..3141b116b7a 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -153,6 +153,14 @@ typedef enum UpperRelationKind
 	/* NB: UPPERREL_FINAL must be last enum entry; it's used to size arrays */
 } UpperRelationKind;
 
+/* Private workspace for planning the SELECT input of a top-level INSERT. */
+typedef struct ParallelInsertInfo
+{
+	Index		source_rti;		/* SELECT's RT index in the INSERT */
+	struct TupleBuffer *buffer; /* provisional buffer, if one was added */
+	Bitmapset  *plan_deps;		/* setrefs: SubPlan IDs, or zero for Gather */
+} ParallelInsertInfo;
+
 /*----------
  * PlannerGlobal
  *		Global information for planning/optimization
@@ -253,6 +261,9 @@ typedef struct PlannerGlobal
 	/* parallel mode potentially OK? */
 	bool		parallelModeOK;
 
+	/* workspace for a top-level INSERT with a separately planned SELECT */
+	ParallelInsertInfo *parallelInsert pg_node_attr(read_write_ignore);
+
 	/* parallel mode actually required? */
 	bool		parallelModeNeeded;
 
@@ -2360,6 +2371,26 @@ typedef struct MaterialPath
 	Path	   *subpath;
 } MaterialPath;
 
+/*
+ * TupleBufferPath represents a TupleBuffer node.  With buffer_if_parallel
+ * unset, the node reads its entire input into a tuplestore before returning
+ * the first tuple.
+ *
+ * INSERT ... SELECT sets buffer_if_parallel to request buffering only if
+ * the final SELECT plan uses parallelism, so workers finish before the
+ * first write.  The flag does not mean the source is known to be parallel.
+ * If no Gather or Gather Merge is built, plan creation omits the buffer.
+ * If setrefs discards the only parallel alternative, the node remains but
+ * passes tuples through without storing them.  A conditional buffer can
+ * therefore promise mark/restore only if its subpath supports it.
+ */
+typedef struct TupleBufferPath
+{
+	Path		path;
+	Path	   *subpath;
+	bool		buffer_if_parallel;
+} TupleBufferPath;
+
 /*
  * MemoizePath represents a Memoize plan node, i.e., a cache that caches
  * tuples from parameterized paths to save the underlying node from having to
diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h
index 10f6b105f91..d27badaad81 100644
--- a/src/include/nodes/plannodes.h
+++ b/src/include/nodes/plannodes.h
@@ -1084,6 +1084,19 @@ typedef struct Material
 	Plan		plan;
 } Material;
 
+typedef enum TupleBufferMode
+{
+	TUPLEBUFFER_EAGER,			/* buffer the entire input */
+	TUPLEBUFFER_PARALLEL,		/* do so in the INSERT's parallel read phase */
+	TUPLEBUFFER_PASSTHROUGH		/* the final INSERT source is serial */
+} TupleBufferMode;
+
+typedef struct TupleBuffer
+{
+	Plan		plan;
+	TupleBufferMode mode;
+} TupleBuffer;
+
 /* ----------------
  *		memoize node
  * ----------------
diff --git a/src/include/optimizer/cost.h b/src/include/optimizer/cost.h
index 19f8753e2d8..9f805fa9de3 100644
--- a/src/include/optimizer/cost.h
+++ b/src/include/optimizer/cost.h
@@ -131,6 +131,8 @@ extern void cost_material(Path *path,
 						  bool enabled, int input_disabled_nodes,
 						  Cost input_startup_cost, Cost input_total_cost,
 						  double tuples, int width);
+extern void cost_tuplebuffer(Cost *startup_cost, Cost *total_cost,
+							 Cost input_total_cost, double tuples, int width);
 extern void cost_agg(Path *path, PlannerInfo *root,
 					 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
 					 int numGroupCols, double numGroups,
diff --git a/src/include/optimizer/pathnode.h b/src/include/optimizer/pathnode.h
index e74a95d0d22..d92b4f94e90 100644
--- a/src/include/optimizer/pathnode.h
+++ b/src/include/optimizer/pathnode.h
@@ -116,6 +116,8 @@ extern GroupResultPath *create_group_result_path(PlannerInfo *root,
 												 List *havingqual);
 extern MaterialPath *create_material_path(RelOptInfo *rel, Path *subpath,
 										  bool enabled);
+extern TupleBufferPath *create_tuplebuffer_path(RelOptInfo *rel, Path *subpath,
+												bool buffer_if_parallel);
 extern MemoizePath *create_memoize_path(PlannerInfo *root,
 										RelOptInfo *rel,
 										Path *subpath,
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..c97f43d073e 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2147,6 +2147,7 @@ ParallelHashJoinBatch
 ParallelHashJoinBatchAccessor
 ParallelHashJoinState
 ParallelIndexScanDesc
+ParallelInsertInfo
 ParallelSlot
 ParallelSlotArray
 ParallelSlotResultHandler
@@ -3257,6 +3258,10 @@ TsmRoutine
 TupOutputState
 TupSortStatus
 TupStoreStatus
+TupleBuffer
+TupleBufferMode
+TupleBufferPath
+TupleBufferState
 TupleConstr
 TupleConversionMap
 TupleDesc
-- 
2.56.1

From be2d4818df1286660e6eb69cc2a94c7537056421 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
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

Reply via email to