From 7796fdcd56a87c05c400108e9a66c97754f64800 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
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

