Review
Assert failure in parallel query due to SubPlan double visit for hash join
- Proposal version
- 1
- CommitFest entry
- 7554
- Base commit
- 9ebc9a458c38465cd9609814cfc9ca3a2f46fef5
Summary
Reviewed David Geier's v1 patch
(v1-0001-planstate_tree_walker-visits-every-node-only-once.patch,
posted 2026-11-24) against master at commit
9ebc9a458c38465cd9609814cfc9ca3a2f46fef5. Nothing from this thread has
been committed to master, though commit 303c9b36205 (Fix reuse of
stale hash tables by duplicated hashed SubPlans) recently landed and is
directly relevant to the design.
Verdict: Needs significant redesign before commit. The underlying
bug is genuine and affects all supported branches (assert failure in
shm_toc_insert() and corrupted EXPLAIN ANALYZE worker statistics
when a PlanState tree reaches the same SubPlan PlanState more than
once). However, this v1 discussion draft introduces a silent ABI/API
break on public planstate_tree_walker(), unbounded intra-query memory
leaks in ExecShutdownNode() and ExecParallelReinitialize(), a
per-query palloc regression on queries without SubPlans, and lacks
regression tests, a commit message body, and pgindent /
typedefs.list updates.
Applying, Building, and Testing
- Applies cleanly with
git amon9ebc9a458c38465cd9609814cfc9ca3a2f46fef5(5 files changed:explain.c,execParallel.c,execProcnode.c,nodeFuncs.c,nodeFuncs.h). git diff --check: clean.- Debug/cassert build (
ninja): clean, zero warnings. meson test regress/regress: passed (243/243 subtests).pgindent: fails check — 3 files (explain.c,execParallel.c,execProcnode.c) have formatting differences because 4 new typedefs are missing fromsrc/tools/pgindent/typedefs.listand 6Bitmapsetfield declarations use a single space (Bitmapset *visited;).
Motivation and Root Cause
A PlanState graph is a DAG, not a tree, whenever the same SubPlan
PlanState (estate->es_subplanstates[plan_id - 1]) is referenced via
multiple SubPlanState entries. This happens both within a single node
(e.g., nodeHashjoin.c:1000,1050 building hashkeys and hashclauses
on the same HashJoinState) and across distinct nodes (inner-side hash
keys on HashState vs hashclauses on HashJoinState, partitioned
Append child scans copying a WHERE clause, BitmapIndexScan +
BitmapHeapScan recheck qual, etc.).
Note that David's message 11 remark about deduplicating a single
PlanState's subPlan list is unsafe: ExecReScan() in
src/backend/executor/execAmi.c:112-126 (updated by 303c9b36205) must
walk every SubPlanState in node->subPlan to mark each instance's
hashtablestale = true, because each SubPlanState owns its own hash
table. Deduplication therefore belongs in tree traversal, not in
parent->subPlan.
Detailed Code Findings
1. Silent ABI/API Breakage in planstate_tree_walker() (Blocker)
In src/backend/nodes/nodeFuncs.c, planstate_walk_child() casts the
opaque void *context directly to (Bitmapset **) context and reads
and mutates *visited:
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);
Because planstate_tree_walker() and planstate_tree_walker_impl()
keep their existing void *context signature (nodeFuncs.h:181,220),
every out-of-tree extension calling planstate_tree_walker() (such as
custom scan providers or plan-inspection extensions) compiles without
any warning and then breaks catastrophically at runtime:
- Passing
context == NULL(previously valid; in-coreExecShutdownNode_walker()did this) immediately dereferencesNULLwithSIGSEGV. - Passing a struct whose first field is not
Bitmapset *either crashes inbms_is_member()or, worse, silently corrupts memory: if the first pointer-sized field happens to be zero/NULL,bms_add_member(NULL, plan_node_id)overwrites the caller's first 8 bytes with aBitmapset *. - The change is impossible to backpatch to stable branches (PG 14-19),
even though the crash and stats corruption have existed since PG 10
(
b8d7f053c5c).
All 8 in-core callers (explain.c:1250, execParallel.c:355,612,1105, 1198,1414,1527, execProcnode.c:779; 0 in contrib/) were updated,
but changing the runtime contract of an exported void * API is not
acceptable.
2. Unbounded Intra-Query Memory Leaks & Hot-Path Allocations (Major)
bms_free() is never called at any call site. Checking
CurrentMemoryContext at every caller reveals two unbounded intra-query
leaks into estate->es_query_cxt plus a universal hot-path allocation
regression:
ExecShutdownNode()(execProcnode.c:753): Called fromExecutePlan()(execMain.c:1824) insidestandard_ExecutorRun()withCurrentMemoryContext == estate->es_query_cxton every non-backward-scrollableExecutorRun()invocation, including bounded fetches (numberTuples > 0). This affects lazy SQL SRFs (functions.c:1424-1426,count = 1: one leakedBitmapsetper returned row),NO SCROLLcursors (FETCH N), PL/pgSQLFORloops (50 rows per fetch), and extended-protocolExecutewithmax_rows. Furthermore,ExecShutdownNode()previously did zero allocations; this patch adds apalloc(andrepallocs on large partitioned plans) to every query with >= 2 plan nodes, even simple OLTP queries with no SubPlans and no parallelism.ExecParallelReinitialize()(execParallel.c:987): Called on every rescan ofGather/GatherMerge(e.g., on the inner side of a Nested Loop) ines_query_cxt. Each rescan leaksrcxt.visited.- The remaining callers (
ExecInitParallelPlan,ExecParallelCleanup,ParallelQueryMain,ExplainPrintPlan) have bounded leaks, yet each owns the stack context right after the walk finishes and could trivially callbms_free().
3. Design Alternative: SubPlan-Only Tracking & ABI-Safe Entrypoint
In PostgreSQL PlanState graphs, shared nodes arise exclusively through
planstate_walk_subplans() (initPlan and subPlan).
ExplainSubPlans() (explain.c:5231-5244) already deduplicates shared
subplans via SubPlan->plan_id (es->printed_subplans).
Tracking SubPlan->plan_id (rather than every plan->plan_node_id) in
an ABI-preserving design — either per-caller Bitmapset *visited in
execParallel.c + execProcnode.c (as Tomas Vondra proposed) or a new
wrapper function around planstate_tree_walker() that handles cleanup —
solves every issue at once:
- Zero ABI/API break on
planstate_tree_walker()and trivially backpatchable to PG 14-19. - Zero
pallocs and zeroBitmapsetoverhead on the 99%+ of queries that contain no SubPlans (eliminating theExecShutdownNode()OLTP regression). - Avoids fragility if an extension constructs synthetic
Plannodes without runningset_plan_references()(where multiple nodes default toplan_node_id == 0, causing this patch to skip them silently). - Naturally preserves nested
InstrStartNode()/InstrStopNode()inExecShutdownNode_walker()and frees theBitmapsetupon exit.
4. Minor Issues and Packaging Gaps
- Root node omitted from
visited: Top-level callers invokewalker(root, &ctx)directly, so the root'splan_node_idis never added to*visited. While standard plans do not cycle back to root, the header comment ("visits each planstate node exactly once") is inaccurate (it is also "at most once" on earlyreturn true). - Missing regression tests: Neither Lukas's HashJoin reproducer nor his partitioned-table Parallel Append reproducer is included.
- Empty commit message body: Only a one-line subject with no explanation of the bug or design.
- Formatting and cleanup: Add any new typedefs to
src/tools/pgindent/typedefs.list, runpgindent, restore the removed comments onExecParallelEstimateContext/ExecParallelInitializeDSMContext, align prototype parameter names with definitions (r/rcxt,i/icxt), and drop the now-redundantpg_attribute_no_sanitize_function()from functions that no longer callwalkerdirectly (planstate_tree_walker_impl,planstate_walk_subplans,planstate_walk_members).
Community Discussion and Consensus
Ten substantive messages from Lukas Fittl, Sami Imseih, David Geier, and
Tomas Vondra. Everyone agrees the bug is real and prefers a Bitmapset
over adding traversal state to PlanState. However, three competing
approaches remain on the table (Lukas's planstate_tree_collect(),
Tomas's execParallel.c-isolated contexts, and David's global
planstate_tree_walker() contract change). Notably, Tomas explicitly
argued in message 10 against a shared context base pattern and favored
isolating tracking to execParallel.c, whereas David's v1 modifies
planstate_tree_walker() globally. Tomas's question on root cause vs
symptom remains open, backpatching has not been discussed, and nobody
has reviewed v1 yet.
Scores
- Assessment (32/100): Real bug and clean compilation, but v1 is an
early discussion draft with blocking defects: silent ABI/API breakage
and memory-corruption risk for extensions, un-backpatchable design,
unbounded intra-query memory leaks and OLTP allocation overhead, no
tests, empty commit message, and
pgindent/typedefs.listissues. - Consensus (30/100): Agreement on the problem and
Bitmapsetdirection, but competing designs remain unresolved, v1 diverges from Tomas Vondra's stated preference, and v1 has not yet been reviewed on the list.