Hi Tomas!
> Wouldn't it be easier to just have a special context struct for each of
> the functions in execParallel.c that need it? ExecParallelEstimate
> already has ExecParallelEstimateContext (so we could add the bitmap
> there), and we'd get similar contexts for the other functions that need
> to check if the node was already visited (with the bitmap + their
> current context). So we'd get something like
>
> /* Context object for ExecParallelReInitializeDSM. */
> typedef struct ExecParallelReInitializeDSMContext
> {
> ParallelContext *pcxt;
> Bitmapset *visited;
> } ExecParallelReInitializeDSMContext;
>
> typedef struct ExecParallelInstrumentationContext
> {
> SharedExecutorInstrumentation *instrumentation;
> Bitmapset *visited;
> } ExecParallelInstrumentationContext;
>
> ...
>
> I don't see a point to have some "context" ancestor for all these
> contexts, they don't seem to have all that common, no? What would be the
> point of that? All the functions already get a context, and we'd just
> replace that with the new struct (and then get the original one from
> it). Maybe this is what's proposed, though?
I'm intending to change planstate_tree_walker() to never visited the
same node twice; not the specific code that has problems with it in
execParallel.c.
I had thought about something like the following code, with the
motivation of making it obvious to client code that extra state needs to
be passed. I thought that without it, it's too easy to forget embedding
the extra Bitmapset in the context struct.
We cannot simply check for the presence of a Bitmapset member via
Assert(IsA(context, Bitmapset)) in planstate_tree_walker() because
initially the Bitmapset is NULL.
struct PlanStateWalkerContext
{
Bitmapset *visited;
};
struct MyContext
{
PlanStateWalkerContext walker_ctx;
int my_data;
};
planstate_tree_walker_impl(PlanState *planstate,
planstate_tree_walker_callback walker,
PlanStateWalkerContext *context)
MyContext ctx;
planstate_tree_walker(node, &ctx.walker_ctx);
Attached patch does what you proposed as a starting point for more
targeted discussion. The Bitmapset *visited is not cleaned up by
planstate_tree_walker() because it doesn't know when the recursion is
over. For now I'm leaving cleanup to the surrounding memory context. If
we want to free the Bitmapset after traversal, we would need some
wrapper around planstate_tree_walker().
The patch passes both test cases from Lukas and the regression tests.
> Are we maybe addressing a symptom and not the root cause? I mean, this
> code mostly assumes that nodes are a tree, and a single plan can't be
> referenced from multiple nodes. Maybe having the bitmap fixes the
> immediate symptom, but it needs a bigger change? I don't know what that
> would be, though :-(
>
> ISTM all of this sharing can only happen through a subplan. Or can it
> happen in other ways too?
That's what we had discussed a few mails back. There are two cases:
1. A single PlanState contains more than a single reference to the same
PlanState. This case is bogus and could be fixed by not adding the
PlanState again if it exists already.
2. Multiple PlanStates each having a single reference to the same
PlanState. Lukas showed how this can happen. That case makes sense
and I wouldn't know of how to avoid that.
--
David Geier
From fab67786f2d357d1fef3bfedaf225d5476f5ee30 Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Tue, 24 Nov 2026 10:11:53 +0100
Subject: [PATCH v1] planstate_tree_walker() visits every node only once
---
src/backend/commands/explain.c | 21 +++++--
src/backend/executor/execParallel.c | 91 +++++++++++++++++++----------
src/backend/executor/execProcnode.c | 10 ++--
src/backend/nodes/nodeFuncs.c | 28 ++++++++-
src/include/nodes/nodeFuncs.h | 6 ++
5 files changed, 114 insertions(+), 42 deletions(-)
diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c
index 4b1ad4227ac..ed27ebc709c 100644
--- a/src/backend/commands/explain.c
+++ b/src/backend/commands/explain.c
@@ -74,7 +74,15 @@ static void ExplainPrintSerialize(ExplainState *es,
static void report_triggers(ResultRelInfo *rInfo, bool show_relname,
ExplainState *es);
static double elapsed_time(instr_time *starttime);
-static bool ExplainPreScanNode(PlanState *planstate, Bitmapset **rels_used);
+
+typedef struct ExplainPreScanContext
+{
+ Bitmapset *visited;
+ Bitmapset *rels_used;
+} ExplainPreScanContext;
+
+static bool ExplainPreScanNode(PlanState *planstate,
+
ExplainPreScanContext *context);
static void ExplainNode(PlanState *planstate, List *ancestors,
const char *relationship, const
char *plan_name,
ExplainState *es);
@@ -766,7 +774,7 @@ ExplainPrintSettings(ExplainState *es)
void
ExplainPrintPlan(ExplainState *es, QueryDesc *queryDesc)
{
- Bitmapset *rels_used = NULL;
+ ExplainPreScanContext context = {NULL, NULL};
PlanState *ps;
ListCell *lc;
@@ -774,8 +782,8 @@ ExplainPrintPlan(ExplainState *es, QueryDesc *queryDesc)
Assert(queryDesc->plannedstmt != NULL);
es->pstmt = queryDesc->plannedstmt;
es->rtable = queryDesc->plannedstmt->rtable;
- ExplainPreScanNode(queryDesc->planstate, &rels_used);
- es->rtable_names = select_rtable_names_for_explain(es->rtable,
rels_used);
+ ExplainPreScanNode(queryDesc->planstate, &context);
+ es->rtable_names = select_rtable_names_for_explain(es->rtable,
context.rels_used);
es->deparse_cxt = deparse_context_for_plan_tree(queryDesc->plannedstmt,
es->rtable_names);
es->printed_subplans = NULL;
@@ -1187,9 +1195,10 @@ elapsed_time(instr_time *starttime)
* that never appear in the EXPLAIN output (such as inheritance parents).
*/
static bool
-ExplainPreScanNode(PlanState *planstate, Bitmapset **rels_used)
+ExplainPreScanNode(PlanState *planstate, ExplainPreScanContext *context)
{
Plan *plan = planstate->plan;
+ Bitmapset **rels_used = &context->rels_used;
switch (nodeTag(plan))
{
@@ -1245,7 +1254,7 @@ ExplainPreScanNode(PlanState *planstate, Bitmapset
**rels_used)
break;
}
- return planstate_tree_walker(planstate, ExplainPreScanNode, rels_used);
+ return planstate_tree_walker(planstate, ExplainPreScanNode, context);
}
/*
diff --git a/src/backend/executor/execParallel.c
b/src/backend/executor/execParallel.c
index 38549fd4ab9..50abacb8e6d 100644
--- a/src/backend/executor/execParallel.c
+++ b/src/backend/executor/execParallel.c
@@ -111,25 +111,44 @@ struct SharedExecutorInstrumentation
* follows.
*/
};
+
#define GetInstrumentationArray(sei) \
(StaticAssertVariableIsOfTypeMacro(sei, SharedExecutorInstrumentation
*), \
(NodeInstrumentation *) (((char *) sei) + sei->instrument_offset))
-/* Context object for ExecParallelEstimate. */
typedef struct ExecParallelEstimateContext
{
+ Bitmapset *visited;
ParallelContext *pcxt;
int nnodes;
} ExecParallelEstimateContext;
-/* Context object for ExecParallelInitializeDSM. */
typedef struct ExecParallelInitializeDSMContext
{
+ Bitmapset *visited;
ParallelContext *pcxt;
SharedExecutorInstrumentation *instrumentation;
int nnodes;
} ExecParallelInitializeDSMContext;
+typedef struct ExecParallelReInitializeDSMContext
+{
+ Bitmapset *visited;
+ ParallelContext *pcxt;
+} ExecParallelReInitializeDSMContext;
+
+typedef struct ExecParallelInstrumentationContext
+{
+ Bitmapset *visited;
+ SharedExecutorInstrumentation *instrumentation;
+} ExecParallelInstrumentationContext;
+
+typedef struct ExecParallelInitializeWorkerContext
+{
+ Bitmapset *visited;
+ ParallelWorkerContext *pwcxt;
+} ExecParallelInitializeWorkerContext;
+
/* Helper functions that run in the parallel leader. */
static char *ExecSerializePlan(Plan *plan, EState *estate);
static bool ExecParallelEstimate(PlanState *planstate,
@@ -139,9 +158,9 @@ static bool ExecParallelInitializeDSM(PlanState *planstate,
static shm_mq_handle **ExecParallelSetupTupleQueues(ParallelContext *pcxt,
bool reinitialize);
static bool ExecParallelReInitializeDSM(PlanState *planstate,
-
ParallelContext *pcxt);
+
ExecParallelReInitializeDSMContext *r);
static bool ExecParallelRetrieveInstrumentation(PlanState *planstate,
-
SharedExecutorInstrumentation *instrumentation);
+
ExecParallelInstrumentationContext *i);
/* Helper function that runs in the parallel worker. */
static DestReceiver *ExecParallelGetReceiver(dsm_segment *seg, shm_toc *toc);
@@ -664,8 +683,8 @@ ExecInitParallelPlan(PlanState *planstate, EState *estate,
{
ParallelExecutorInfo *pei;
ParallelContext *pcxt;
- ExecParallelEstimateContext e;
- ExecParallelInitializeDSMContext d;
+ ExecParallelEstimateContext e = {0};
+ ExecParallelInitializeDSMContext d = {0};
FixedParallelExecutorState *fpes;
char *pstmt_data;
char *pstmt_space;
@@ -762,7 +781,6 @@ ExecInitParallelPlan(PlanState *planstate, EState *estate,
* count of how many PlanState nodes there are.
*/
e.pcxt = pcxt;
- e.nnodes = 0;
ExecParallelEstimate(planstate, &e);
/* Estimate space for instrumentation, if required. */
@@ -924,7 +942,6 @@ ExecInitParallelPlan(PlanState *planstate, EState *estate,
*/
d.pcxt = pcxt;
d.instrumentation = instrumentation;
- d.nnodes = 0;
/* Install our DSA area while initializing the plan. */
estate->es_query_dsa = pei->area;
@@ -980,6 +997,7 @@ ExecParallelReinitialize(PlanState *planstate,
{
EState *estate = planstate->state;
FixedParallelExecutorState *fpes;
+ ExecParallelReInitializeDSMContext rcxt = {NULL, pei->pcxt};
/* Old workers must already be shut down */
Assert(pei->finished);
@@ -1015,7 +1033,7 @@ ExecParallelReinitialize(PlanState *planstate,
/* Traverse plan tree and let each child node reset associated state. */
estate->es_query_dsa = pei->area;
- ExecParallelReInitializeDSM(planstate, pei->pcxt);
+ ExecParallelReInitializeDSM(planstate, &rcxt);
estate->es_query_dsa = NULL;
}
@@ -1024,7 +1042,7 @@ ExecParallelReinitialize(PlanState *planstate,
*/
static bool
ExecParallelReInitializeDSM(PlanState *planstate,
- ParallelContext *pcxt)
+
ExecParallelReInitializeDSMContext *rcxt)
{
if (planstate == NULL)
return false;
@@ -1037,46 +1055,46 @@ ExecParallelReInitializeDSM(PlanState *planstate,
case T_SeqScanState:
if (planstate->plan->parallel_aware)
ExecSeqScanReInitializeDSM((SeqScanState *)
planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_IndexScanState:
if (planstate->plan->parallel_aware)
ExecIndexScanReInitializeDSM((IndexScanState *)
planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_IndexOnlyScanState:
if (planstate->plan->parallel_aware)
ExecIndexOnlyScanReInitializeDSM((IndexOnlyScanState *) planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_ForeignScanState:
if (planstate->plan->parallel_aware)
ExecForeignScanReInitializeDSM((ForeignScanState *) planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_TidRangeScanState:
if (planstate->plan->parallel_aware)
ExecTidRangeScanReInitializeDSM((TidRangeScanState *) planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_AppendState:
if (planstate->plan->parallel_aware)
- ExecAppendReInitializeDSM((AppendState *)
planstate, pcxt);
+ ExecAppendReInitializeDSM((AppendState *)
planstate, rcxt->pcxt);
break;
case T_CustomScanState:
if (planstate->plan->parallel_aware)
ExecCustomScanReInitializeDSM((CustomScanState
*) planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_BitmapHeapScanState:
if (planstate->plan->parallel_aware)
ExecBitmapHeapReInitializeDSM((BitmapHeapScanState *) planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_HashJoinState:
if (planstate->plan->parallel_aware)
ExecHashJoinReInitializeDSM((HashJoinState *)
planstate,
-
pcxt);
+
rcxt->pcxt);
break;
case T_BitmapIndexScanState:
case T_HashState:
@@ -1091,7 +1109,7 @@ ExecParallelReInitializeDSM(PlanState *planstate,
break;
}
- return planstate_tree_walker(planstate, ExecParallelReInitializeDSM,
pcxt);
+ return planstate_tree_walker(planstate, ExecParallelReInitializeDSM,
rcxt);
}
/*
@@ -1100,8 +1118,9 @@ ExecParallelReInitializeDSM(PlanState *planstate,
*/
static bool
ExecParallelRetrieveInstrumentation(PlanState *planstate,
-
SharedExecutorInstrumentation *instrumentation)
+
ExecParallelInstrumentationContext *icxt)
{
+ SharedExecutorInstrumentation *instrumentation = icxt->instrumentation;
NodeInstrumentation *instrument;
int i;
int n;
@@ -1182,7 +1201,7 @@ ExecParallelRetrieveInstrumentation(PlanState *planstate,
}
return planstate_tree_walker(planstate,
ExecParallelRetrieveInstrumentation,
-
instrumentation);
+ icxt);
}
/*
@@ -1286,8 +1305,10 @@ ExecParallelCleanup(ParallelExecutorInfo *pei)
{
/* Accumulate instrumentation, if any. */
if (pei->instrumentation)
- ExecParallelRetrieveInstrumentation(pei->planstate,
-
pei->instrumentation);
+ {
+ ExecParallelInstrumentationContext icxt = {NULL,
pei->instrumentation};
+ ExecParallelRetrieveInstrumentation(pei->planstate, &icxt);
+ }
/* Accumulate JIT instrumentation, if any. */
if (pei->jit_instrumentation)
@@ -1367,8 +1388,9 @@ ExecParallelGetQueryDesc(shm_toc *toc, DestReceiver
*receiver,
*/
static bool
ExecParallelReportInstrumentation(PlanState *planstate,
-
SharedExecutorInstrumentation *instrumentation)
+
ExecParallelInstrumentationContext *icxt)
{
+ SharedExecutorInstrumentation *instrumentation = icxt->instrumentation;
int i;
int plan_node_id = planstate->plan->plan_node_id;
NodeInstrumentation *instrument;
@@ -1398,7 +1420,7 @@ ExecParallelReportInstrumentation(PlanState *planstate,
InstrAggNode(&instrument[ParallelWorkerNumber], planstate->instrument);
return planstate_tree_walker(planstate,
ExecParallelReportInstrumentation,
-
instrumentation);
+ icxt);
}
/*
@@ -1407,8 +1429,11 @@ ExecParallelReportInstrumentation(PlanState *planstate,
* is allocated and initialized by executor; that is, after ExecutorStart().
*/
static bool
-ExecParallelInitializeWorker(PlanState *planstate, ParallelWorkerContext
*pwcxt)
+ExecParallelInitializeWorker(PlanState *planstate,
+
ExecParallelInitializeWorkerContext *wcxt)
{
+ ParallelWorkerContext *pwcxt = wcxt->pwcxt;
+
if (planstate == NULL)
return false;
@@ -1506,7 +1531,7 @@ ExecParallelInitializeWorker(PlanState *planstate,
ParallelWorkerContext *pwcxt)
}
return planstate_tree_walker(planstate, ExecParallelInitializeWorker,
- pwcxt);
+ wcxt);
}
/*
@@ -1539,6 +1564,7 @@ ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
void *area_space;
dsa_area *area;
ParallelWorkerContext pwcxt;
+ ExecParallelInitializeWorkerContext wcxt = {0};
/* Get fixed-size state. */
fpes = shm_toc_lookup(toc, PARALLEL_KEY_EXECUTOR_FIXED, false);
@@ -1577,7 +1603,8 @@ ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
}
pwcxt.toc = toc;
pwcxt.seg = seg;
- ExecParallelInitializeWorker(queryDesc->planstate, &pwcxt);
+ wcxt.pwcxt = &pwcxt;
+ ExecParallelInitializeWorker(queryDesc->planstate, &wcxt);
/* Pass down any tuple bound */
ExecSetTupleBound(fpes->tuples_needed, queryDesc->planstate);
@@ -1610,8 +1637,10 @@ ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
/* Report instrumentation data if any instrumentation options are set.
*/
if (instrumentation != NULL)
- ExecParallelReportInstrumentation(queryDesc->planstate,
-
instrumentation);
+ {
+ ExecParallelInstrumentationContext icxt = {NULL,
instrumentation};
+ ExecParallelReportInstrumentation(queryDesc->planstate, &icxt);
+ }
/* Report JIT instrumentation data if any */
if (queryDesc->estate->es_jit && jit_instrumentation != NULL)
diff --git a/src/backend/executor/execProcnode.c
b/src/backend/executor/execProcnode.c
index 7c4c66e323f..af2d631074c 100644
--- a/src/backend/executor/execProcnode.c
+++ b/src/backend/executor/execProcnode.c
@@ -121,7 +121,7 @@
#include "nodes/nodeFuncs.h"
static TupleTableSlot *ExecProcNodeFirst(PlanState *node);
-static bool ExecShutdownNode_walker(PlanState *node, void *context);
+static bool ExecShutdownNode_walker(PlanState *node, Bitmapset **visited);
/* ------------------------------------------------------------------------
@@ -752,11 +752,13 @@ ExecEndNode(PlanState *node)
void
ExecShutdownNode(PlanState *node)
{
- (void) ExecShutdownNode_walker(node, NULL);
+ Bitmapset *visited = NULL;
+
+ (void) ExecShutdownNode_walker(node, &visited);
}
static bool
-ExecShutdownNode_walker(PlanState *node, void *context)
+ExecShutdownNode_walker(PlanState *node, Bitmapset **visited)
{
if (node == NULL)
return false;
@@ -776,7 +778,7 @@ ExecShutdownNode_walker(PlanState *node, void *context)
if (node->instrument && node->instrument->running)
InstrStartNode(node->instrument);
- planstate_tree_walker(node, ExecShutdownNode_walker, context);
+ planstate_tree_walker(node, ExecShutdownNode_walker, visited);
switch (nodeTag(node))
{
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 678b9a046ce..c045307304c 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -4732,6 +4732,32 @@ raw_expression_tree_walker_impl(Node *node,
return false;
}
+/*
+ * planstate_walk_child --- invoke walker callback on a child planstate node
+ *
+ * The plan state tree is not necessarily a tree: a shared subplan can make
+ * the same node reachable through multiple paths. To ensure that each node
+ * is visited only once, we track visited nodes by their plan_node_id in a
+ * Bitmapset, which by convention must be the first member of the context
+ * passed to the walker callback.
+ */
+pg_attribute_no_sanitize_function()
+static bool
+planstate_walk_child(PlanState *planstate,
+ planstate_tree_walker_callback walker,
+ void *context)
+{
+ Bitmapset **visited = (Bitmapset **) context;
+
+ if (planstate == NULL)
+ return false;
+ if (bms_is_member(planstate->plan->plan_node_id, *visited))
+ return false;
+
+ *visited = bms_add_member(*visited, planstate->plan->plan_node_id);
+ return walker(planstate, context);
+}
+
/*
* planstate_tree_walker --- walk plan state trees
*
@@ -4748,7 +4774,7 @@ planstate_tree_walker_impl(PlanState *planstate,
ListCell *lc;
/* We don't need implicit coercions to Node here */
-#define PSWALK(n) walker(n, context)
+#define PSWALK(n) planstate_walk_child(n, walker, context)
/* Guard against stack overflow due to overly complex plan trees */
check_stack_depth();
diff --git a/src/include/nodes/nodeFuncs.h b/src/include/nodes/nodeFuncs.h
index 696ffdebd4b..b55512f0a15 100644
--- a/src/include/nodes/nodeFuncs.h
+++ b/src/include/nodes/nodeFuncs.h
@@ -178,6 +178,12 @@ extern bool check_functions_in_node(Node *node,
check_function_callback checker,
#define raw_expression_tree_walker(n, w, c) \
raw_expression_tree_walker_impl(n, (tree_walker_callback) (w), c)
+/*
+ * planstate_tree_walker visits each planstate node exactly once, even if it
+ * is reachable through multiple paths (e.g. shared subplans). To support
+ * this, the first member of the context struct passed to the callback must
+ * be a Bitmapset *, which the walker uses to track visited plan_node_ids.
+ */
#define planstate_tree_walker(ps, w, c) \
planstate_tree_walker_impl(ps, (planstate_tree_walker_callback) (w), c)
--
2.55.0