Review
Show hashed ScalarArrayOpExpr decision in EXPLAIN (v1)
- Proposal version
- 1
- Base commit
- 412848dac37f2e4455e1505f83f0af0f3d28a67d
Summary
The patch makes ruleutils.c print hashed before ANY/ALL when a
ScalarArrayOpExpr carries a hashfuncid, so EXPLAIN shows whether the
executor will probe a hash table or scan the array linearly; it also
adds regression tests for the hashed/non-hashed decision (including
the container-type cases of commit 06e94eccfd9, which shipped without
tests). The C change is ten lines, mirrors the existing hashed SubPlan N marker, and is correct: the marker tracks exactly the field
the executor consults, it is decided at plan time, and it cannot leak
into views, rules, constraints, pg_dump output or any other stored
expression (verified for every stored-expression kind). Two points
need a committer's judgement: Index Cond lines now say hashed
although the index AM, not a hash table, evaluates that array; and the
patch immediately exposes a pre-existing v18 planner regression
(GROUP BY expressions are never hash-converted since the GROUP RTE
commit 247dea89f76), which should be fixed separately. Small nits in
the comment wording, a test-comment typo and two missing test cases
remain. I agree the entry is essentially ready for committer; the
"Missing Tests" tag is stale.
What was reviewed
- Series: v1, 1 patch, from message 23833a20-ace1-484b-b176-18cd32c6cdf6@gmail.com (CommitFest entry 6868), author Andrei Lepikhov. The original attachment is byte-identical to what the CF bot applied (tree diff empty).
- Applied on: 412848dac37f2e4455e1505f83f0af0f3d28a67d ("Treat any negative ws_file as closed in xlogreader.c", master), cleanly by cherry-pick from the bot's base 98c41fed6fc.
- Built: meson, debug, cassert, injection points, TAP, lz4/zstd/
liburing/libnuma/icu,
-Wtype-limits -Werror=missing-braces; new warnings: none. A secondrelease/cassert-off build was used for timing only. - Ran:
meson test --suite setup --suite regress(239 subtests OK); fullmeson test(393 OK, 0 failed, 35 skipped, all skips are environment-gated: kerberos, ldap, oauth, sspi, test_checksums); regress again withPGOPTIONS='-c debug_parallel_query=regress'(239 subtests OK); pgindent on ruleutils.c;git diff --checkclean. Ad-hoc: EXPLAIN in TEXT/JSON/YAML/XML, with and without VERBOSE, ANALYZE, JIT, parallel plans, Index/Index Only/Bitmap scans, Join Filter, One-Time Filter, Sort/Group/Window keys, HAVING, CTEs, partitioned tables, UPDATE; prepared statements underforce_custom_plan/force_generic_plan,EXPLAIN (GENERIC_PLAN), plpgsql cached plans, inlined SQL functions; deparse of view, rule, CHECK, domain CHECK, index expression and predicate, column default, generated column, trigger WHEN, policy, extended statistics, partition bound and partition constraint, plus a fullpg_dumpof that database grepped for the marker; postgres_fdw loopbackRemote SQL.
Motivation and scope
Since v14 (50e17ad281b) the executor evaluates x = ANY(const array)
with at least MIN_ARRAY_SIZE_FOR_HASHED_SAOP (9) elements by probing
a hash table, provided the operator is hashable, both sides use the
same hash function and (for <> ALL) a negator exists. The decision
is made by convert_saop_to_hashed_saop() and stored in
ScalarArrayOpExpr.hashfuncid, which ExecInitExprRec() consults
(src/backend/executor/execExpr.c, if (OidIsValid(opexpr->hashfuncid))
selects EEOP_HASHED_SCALARARRAYOP). EXPLAIN gave no hint, so a user
with a long IN list could not tell whether the fallback (linear scan,
O(n) per row) was being used, e.g. after commit 06e94eccfd9 started
refusing to hash container types with non-hashable members. The
parent thread (pgsql-bugs, ed221f95-f09b-4a9c-b05b-e1fed621ec87)
shows a 12x runtime swing between the two strategies on a 9-element
record array.
Scope is minimal: one deparse site in get_rule_expr() for
T_ScalarArrayOpExpr, plus tests in expressions, rangetypes and
rowtypes. No planner or executor behaviour changes.
Design and alternatives
The chosen form, (x = hashed ANY ('{...}'::integer[])), follows the
precedent of (hashed SubPlan 1) / NOT (hashed SubPlan 1) in the
same file (ruleutils.c, subplan->useHashTable ? "hashed " : ""). It
is printed unconditionally (not only with VERBOSE), in every format
as part of the expression string, and never as a separate property.
Reviewer Nishant Sharma floated also printing linear for the
non-hashed case and withdrew it himself (too many expected-output
changes, little information). I agree: absence of the marker is the
common case and is already how SubPlans are shown.
Alternatives a committer might weigh:
- A separate property (e.g.
Hashed Array: ...) would be structured for JSON consumers but does not work when several SAOPs appear in one expression, and no existing per-expression decision is presented that way. - Printing only under VERBOSE would protect third-party expected outputs but would hide the information from the plain EXPLAIN most users run; the SubPlan marker is unconditional too.
Where the information comes from matters for the semantics:
convert_saop_to_hashed_saop() runs in preprocess_expression()
(src/backend/optimizer/plan/planner.c, kind == EXPRKIND_QUAL || kind == EXPRKIND_TARGET), i.e. before path generation. Consequently the
marker appears wherever the planner copies the qual: scan Filter,
Join Filter, One-Time Filter, Recheck Cond, target lists, Sort/
Group/Window keys, and Index Cond. For Index Cond this is
misleading, see Correctness/Design finding 1.
Correctness
I found no correctness problem in the patch. What I tried:
- The marker is driven by the exact field the executor tests, so it
cannot disagree with execution:
EXPLAINwithout ANALYZE shows the same text asEXPLAIN ANALYZE; JIT compiles the same step. - Plan time vs. prepared statements: with
plan_cache_mode = force_custom_plan,x = ANY($1)with a 9-element argument printshashed(the Param is folded to a Const); withforce_generic_planit prints(x = ANY ($1)), andEXPLAIN (GENERIC_PLAN)likewise. Both are correct: the generic plan really does scan linearly. A 9-element literal list next to$1is hashed in both modes. This is a genuinely useful thing for users to be able to see. - Leak into stored expressions:
pg_get_viewdef,pg_get_ruledef,pg_get_constraintdef(table and domain),pg_get_indexdef(expression and predicate),pg_get_expron column default, generated column,relpartbound,pg_get_partition_constraintdef,pg_get_triggerdef(WHEN),pg_policies.qual,CREATE STATISTICSexpressions and a completepg_dumpof that database (166 lines) never containhashed, even after the same objects had been planned and executed. This holds by construction:hashfuncidis only assigned inconvert_saop_to_hashed_saop(), called only frompreprocess_expression()on the planner's private copy of the query;expression_planner()(used for defaults, CHECK constraints, index expressions, partition constraints) does not call it; and users cannot feed node strings topg_get_expr(pg_node_tree has no usable input function). The in-coredeparse_expression()callers other than explain.c (parse_utilcmd.c partition-key column names, typecmds.c domain defaults) operate on parser output. - postgres_fdw:
Remote SQLcomes from contrib/postgres_fdw/deparse.c, which ignoreshashfuncid; the remote query is unchanged while a locally evaluatedOutput:expression does showhashed, which is right. - Partial-index predicate as
Recheck Cond: the predicate comes from the catalog viaRelationGetIndexPredicate()and is not converted, and EXPLAIN correctly shows it unhashed; the executor really does evaluate it linearly on lossy pages. - Formats:
hashedis inside the string value ofFilter/Index Cond; JSON/YAML/XML structure is unchanged.
Finding 1 (design/UX, not a bug): Index Cond prints hashed.
create table t (x int); create index on t (x);
set enable_seqscan = off;
explain (costs off) select * from t where x in (1,2,3,4,5,6,7,8,9);
-- Index Scan using t_x_idx on t
-- Index Cond: (x = hashed ANY ('{1,2,3,4,5,6,7,8,9}'::integer[]))
The same appears for Index Only Scan and for Index Cond of a Bitmap
Index Scan. The index AM handles the array itself (nbtree array keys);
the hash table is built lazily and only if the executor ever
evaluates indexqualorig/bitmapqualorig, i.e. on an EPQ recheck or
a lossy bitmap page. So the statement "the executor will use a hash
table" is true of the node but not of the index scan the user is
looking at. Reviewer Ayush Tiwari "spot-checked a hashed SAOP as an
index condition" and found it "behaves correctly", so the thread has
seen the output but not discussed what it means. Options: accept it
and say so in the comment and a doc sentence (cheap, my preference),
or have explain.c deparse index quals with the marker suppressed
(needs a deparse_context flag; probably not worth it). Either way a
regression test with an Index Cond should pin the chosen behaviour.
Finding 2 (pre-existing planner gap exposed by the patch, outside its scope): GROUP BY expressions are never hash-converted on v18+.
explain (costs off, verbose)
select x in (1,2,3,4,5,6,7,8,9) as h from t;
-- Output: (x = hashed ANY ('{1,2,3,4,5,6,7,8,9}'::integer[]))
explain (costs off, verbose)
select x in (1,2,3,4,5,6,7,8,9) as h from t group by 1;
-- Group Key: (t.x = ANY ('{1,2,3,4,5,6,7,8,9}'::integer[]))
-- -> Seq Scan on public.t
-- Output: (x = ANY ('{1,2,3,4,5,6,7,8,9}'::integer[]))
Since 247dea89f76 ("Introduce an RTE for the grouping step", v18)
grouping expressions live in rte->groupexprs, which
subquery_planner() preprocesses with EXPRKIND_GROUPEXPR;
preprocess_expression() only calls convert_saop_to_hashed_saop()
for EXPRKIND_QUAL/EXPRKIND_TARGET, and flatten_group_exprs()
then substitutes the unconverted copies into the target list and
HAVING. On v17 the same expression was a plain target entry and was
hashed. ORDER BY, window PARTITION BY, HAVING on aggregates and plain
target lists are unaffected. REL_18_STABLE has the same code. Cost,
on 2,000,000 rows with a 1000-element IN list, serial, JIT off; the
two queries reduce to the identical HashAggregate -> Seq Scan shape
(the trivial SubqueryScan is removed), differing only in the marker:
| query (release build, cassert off) | run 1 | run 2 | run 3 |
|---|---|---|---|
| GROUP BY 1 directly (not hashed) | 2493 ms | 2474 ms | 2476 ms |
same via OFFSET 0 subquery (hashed) |
128 ms | 126 ms | 128 ms |
A debug/cassert build showed the same ratio (11.3 s vs 0.49 s).
The fix is one condition in preprocess_expression() (also convert
for EXPRKIND_GROUPEXPR); it is independent of this patch and
deserves its own thread and a back-patch to 18. I mention it here
because it is the first thing the new marker reveals, and it is the
strongest argument for committing the marker.
Performance
n/a for the patch itself: it adds one OidIsValid() test and up to
seven bytes per deparsed SAOP, on the EXPLAIN path only. Timing in
Finding 2 concerns pre-existing planner behaviour, not this change.
Compatibility
- EXPLAIN text changes for every plan containing a hashed SAOP, in
all formats (the token is inside the expression string; no
property is added or renamed). No in-tree expected output other
than the patch's own changed (full test suite passes), but
third-party extension test suites whose expected EXPLAIN output
contains an IN list of 9+ constants will need updating; tools that
render EXPLAIN treat expressions as opaque strings. As with
hashed SubPlan 1,InitPlanand$0, theFilter:text is not pasteable SQL; that was never guaranteed. A release-note entry is warranted. - No catalog, ABI, protocol, pg_dump, pg_upgrade or stored-rule impact (verified above). Not back-patchable, as the author already said on the list.
- No platform concerns: pure string output.
Code, tests, docs, style
- src/backend/utils/adt/ruleutils.c,
get_rule_expr(): the comment "hashfuncid is only ever set in a finished plan tree" is inaccurate (the commit message says the same). It is set early, inpreprocess_expression(), on the planner's working copy of the query, and is present inRelOptInfoquals long before there is a plan. The guarantee that matters is "only the planner sets it, and the planner never writes expressions back to the catalogs". Suggest wording along those lines. pgindent would also reflow the comment into one paragraph. - src/test/regress/sql/expressions.sql: "Check that 'hashed' is actually bubbles up in the explain" (raised by Ayush Tiwari, still present in v1); e.g. "Check that 'hashed' shows up in EXPLAIN".
- Tests present and good: hashed int list; cross-type
int4 = ANY(int8[])not hashed; range and multirange hashed;<> hashed ALLfor NOT IN on numrange; named composite with hashable columns hashed; composite with tsvector column not hashed; anonymous record not hashed; view definition not polluted while EXPLAIN on the view is. The regression gap of 06e94eccfd9 is indeed closed (that commit touched no test files). - Missing tests worth adding: the threshold boundary (8 elements not
hashed, 9 hashed, pinning
MIN_ARRAY_SIZE_FOR_HASHED_SAOP); anIndex Condcase (Finding 1); a non-Const array (= ANY($1)underforce_generic_plan, orANY(ARRAY(SELECT ...))) to show the negative case for parameters. All are a few lines. - Docs: nothing in doc/ describes
hashed SubPlaneither, so no doc update is strictly required; one sentence in perform.sgml near the Filter/Index Cond explanation would help users who meet the new word. The CF "Missing Tests" tag predates v1 and is stale. - Commit message: accurate and well motivated apart from the "finished plan tree" phrase.
Discussion and consensus
Thread: Andrei Lepikhov posted v0 on 2026-06-09 as a follow-up to
the pgsql-bugs thread where Tom Lane committed 06e94eccfd9. In that
parent thread Tom was "unexcited" about the EXPLAIN patch and then
clarified: "0002 is a new feature and hence out of scope at this
point in the development cycle. If you want to start a new thread
proposing that for v20, go right ahead." That is not an endorsement
of the design, only a statement that timing was the objection.
Nishant Sharma reviewed v0 (asked for a view-leak test and multirange
coverage, both added in v1; raised and withdrew a linear marker;
asked about back-patching, answered no). Ayush Tiwari reviewed v1,
spot-checked an index condition and ANY(ARRAY(SELECT)), reported
one typo and set Ready for Committer on 2026-07-16. No further
traffic since. Both reviewers describe themselves as new to the
area; no committer has commented on the chosen wording, on the
Index Cond semantics or on the unconditional (non-VERBOSE) display.
Status Ready for Committer, target v20, CF PG20-3, tags Devtools /
Good First Review / Missing Tests (stale).
Verdict
Ready for committer in substance; I would ask the author for a v2 with the small fixes before the committer picks it up:
- Fix the test-comment typo and the "finished plan tree" wording in the code comment and commit message.
- Add the three cheap tests (8-vs-9 boundary,
Index Cond, non-Const array). - Committer to decide whether
hashedinIndex Condis acceptable as-is (I think yes, with a comment and a doc sentence) or should be suppressed.
Separately, and not blocking this patch: fix the v18 regression in
Finding 2 (EXPRKIND_GROUPEXPR not passed to
convert_saop_to_hashed_saop()), with a back-patch to 18. The
assessment score is held below 80 by the unresolved Index Cond
presentation and the missing tests, not by any defect in the patch.