Review
O(N^3) planning time in choose_plan_name() since 8c49a484e8e
- Proposal version
- 6
- CommitFest entry
- 7454
- Base commit
- 9ebc9a458c38465cd9609814cfc9ca3a2f46fef5
Summary
Reviewed Manu's v6 patch
(v6-0001-Avoid-O-N-3-planning-time-in-choose_plan_name.patch, posted
2026-11-04) plus measurements.txt against master at commit
9ebc9a458c38465cd9609814cfc9ca3a2f46fef5. The patch has not been
committed to master.
Verdict: Strong, clean implementation on master; needs an ABI fix
before backpatching to REL_19_STABLE plus minor comment polish. The
algorithm is mathematically sound, preserves exact subplan names, fixes
both the O(N^3) repeated-name and O(N^2) distinct-name regressions
introduced by 8c49a484e8e (PG 19.0), and adds negligible overhead
below 32 subplans. However, inserting subplanNameHash in the middle of
PlannerGlobal breaks binary ABI for REL_19_STABLE extensions
(including GetPlannerGlobalExtensionState()), which must be addressed
given Robert Haas's intent to backpatch.
Applying, Building, and Testing
- Applies cleanly with
git amon9ebc9a458c38465cd9609814cfc9ca3a2f46fef5(5 files:planner.c,pathnodes.h,subselect.sql,subselect.out,typedefs.list). git diff --check: clean.pgindent: clean (zero diff);SubplanNameEntryandsubplan_name_hashproperly added in sorted order tosrc/tools/pgindent/typedefs.list.- Debug/cassert build (
ninja): clean, zero warnings. - Tests passed:
regress/regress: 243/243 subtests passed.pg_overexplain/regress: passed.pg_plan_advice:regress(9/9) and001_foreign_scan(3/3) passed.pg_stash_advice:regress(2/2) and001_persist(6/6) passed.
Motivation and Design
Commit 8c49a484e8e (PG 19.0) made choose_plan_name() scan
glob->subplanNames linearly for every candidate suffix n = 1, 2, ...
giving O(N^3) planning time for N identically-prefixed subplans (e.g.,
16.6 s vs 18.8 ms in PG 18.6 for 4,000 UNION arms) and O(N^2) for N
distinct user-supplied names. Andreas Fe confirmed a real-world PG 19.0
production regression on generated SQL (planning regressed from 40 ms on
18.7 to 78 ms on 19.0, ~40% CPU in choose_plan_name(), slowing overall
application requests by 3.5-9% across both repeated and distinct names).
v6 directly implements Robert Haas's message 15 hybrid design: stay with
the linear list below SUBPLAN_NAME_HASH_THRESHOLD (32), then build a
simplehash keyed by const char * storing both bool used and
unsigned next_suffix. This reduces both workloads to O(N) while
producing byte-identical subplan names (preserving pg_plan_advice
compatibility) and avoiding NAMEDATALEN truncation bugs from v1.
Detailed Code Findings
1. REL_19_STABLE ABI Break in PlannerGlobal (Backpatch Blocker)
In src/include/nodes/pathnodes.h, v6 places struct subplan_name_hash *subplanNameHash immediately after List *subplanNames (field 6 of
32). While fine on master, applying v6 verbatim to REL_19_STABLE (as
suggested in messages 16, 20, and 21) shifts the byte offset of all 26
subsequent fields in PlannerGlobal by 8 bytes on 64-bit platforms —
including extension_state and extension_state_allocated.
src/include/optimizer/extendplan.h:25 defines
GetPlannerGlobalExtensionState() as a static inline function that
directly accesses glob->extension_state_allocated and
glob->extension_state (used by contrib/pg_plan_advice and third-
party planner extensions). Extensions compiled against PG 19.0 headers
would silently misread PlannerGlobal fields or crash on 19.1.
Furthermore, PlannerGlobal has no 8-byte padding hole (only 7 bytes
after maxParallelHazard and 4 bytes of tail padding after
extension_state_allocated on 64-bit). Moving subplanNameHash to the
very end of PlannerGlobal preserves all existing field offsets, but
still increases sizeof(PlannerGlobal) by 8 bytes, which buildfarm ABI
checkers flag on stable branches (cf. commit bba4e095d25). For
REL_19_STABLE, the field must at minimum be placed at the end of
PlannerGlobal (or a committer must decide whether a size-preserving
backpatch variant is preferred).
2. Correctness & Caller Audit (Verified Sound)
Audited all 6 callers of choose_plan_name() (allpaths.c:2842,
planagg.c:343, subselect.c:228,281,990, prepunion.c:251), all
references to glob->subplanNames, and the simplehash logic:
- Memory context: None of the 6 callers run inside a short-lived
memory context; allocating
subplanNameHashandpstrdup(name)inCurrentMemoryContextmatches existingsubplanNamesandrel_notnullatts_hash(plancat.c:709). - Sync with
subplanNames: Nothing outsidechoose_plan_name()reads or mutatesglob->subplanNames, so the hash cannot drift out of sync. Keepinglappend(glob->subplanNames, ...)maintains struct compatibility for debuggers/extensions at negligible cost. - Node support:
PlannerGlobalhaspg_node_attr(no_copy_equal, no_read, no_query_jumble); markingsubplanNameHashwithread_write_ignorecleanly excludes it from_outPlannerGlobal. AllmakeNode(PlannerGlobal)sites zero-init it. - Initial sizing:
subplan_name_create(CurrentMemoryContext, 32, NULL)allocates 64 buckets (grow_threshold = 57), avoiding an immediate resize during initial 32-entry population. - Edge cases verified: Base-name entry with
used = falselater claimed as an exact name or as a suffixed candidate (foo_1_1thenfoo_1), threshold catch-up after 32 generated names, Robin Hood shifted-bucket payload initialization on!found,SH_GROWpointer safety (no staleentrypointer held acrossadd_subplan_name()), and empty string""safety.
3. Minor Issues and Polish
- Inaccurate comment in
pathnodes.h(patch line 235):/* optional hash table for fast lookup; contains same names as list */is inaccurate —subplanNameHashalso holdsused = falsebase-name entries (e.g.,"expr","setop") that are not insubplanNames. - Stale comment in
choose_plan_name()(patch lines 146-148): Still refers to searching the list of previously-assigned names even thoughsubplan_name_in_use()consults the hash table once built. - Free
SH_STORE_HASHoptimization:SubplanNameEntry(uint32 status; const char *name; bool used; unsigned next_suffix;) is 24 bytes on 64-bit with 7 bytes of padding. Addinguint32 hashafterstatuswith#define SH_STORE_HASHkeepssizeof(SubplanNameEntry)at 24 bytes while eliminating repeatedstrlen()/hash_bytes()andstrcmp()calls on probe collisions and resizes. (Or usinguint8 statusshrinks entries to 16 bytes.) - Minor nits: Document on
enter_subplan_name()thatnamemust already live in planner memory context; clean up mixed spaces/tabs in the#define SH_*block; optionally add regression cases testing a post-used=false->truenumbered suffix (confirmingnext_suffixpreservation) and crossing the 32-name threshold with >32 generated names of a single base name.
Community Discussion and Consensus
Twenty substantive messages across Manu, Ayoub Kazar, Andres Freund, Tom
Lane, Robert Haas, and Andreas Fe. Early alternatives (v1
NAMEDATALEN-truncated dynahash, global counter renumbering breaking
pg_plan_advice, v2-v5 list approaches) converged cleanly onto Robert
Haas's hybrid hash design, which v6 implements directly. Andreas Fe's
production regression report convinced Robert Haas that backpatching to
REL_19_STABLE is warranted. Remaining items before commit: nobody has
reviewed v6's code on-list yet, Andreas Fe has not yet reported
benchmark results on v6, and REL_19_STABLE ABI layout has not been
discussed.
Scores
- Assessment (78/100): Clean, well-benchmarked, mathematically sound
fix for a real PG 19.0 regression that passes core and contrib suites
cleanly; held just below 80 by the
REL_19_STABLEPlannerGlobalABI break and minor comment/polish items. - Consensus (74/100): Strong agreement on both urgency and exact architecture (implementing Robert Haas's proposal), with committer support for backpatching; awaiting on-list code review of v6, reporter confirmation on v6, and backpatch ABI agreement.