[PATCH 0/2] Fix two hash join costing errors in final_cost_hashjoin()
Hi,
This series fixes two independent issues in the hash join costing in
final_cost_hashjoin(), both verified on a Citus cluster (coordinator +
3 data nodes, 1000 warehouses, NVMe storage) running a mixed workload of
TPC-C-style transactions and join-heavy analytical queries.
0001: Multi-column hash keys estimate the bucket size from the largest
single-column ndistinct (the minimum over per-clause fractions), while
the output row count of the same join is estimated under the
independence assumption that calc_joinrel_size_estimate() already makes.
The same cost table therefore holds two contradictory beliefs about one
join: on a 1M x 1M three-column join with 100 distinct values per column
(one row per bucket), hash join is priced at 166,622,722 and never
chosen; with the corrected bucket size it costs 282,717 and runs in
1,946 ms versus 4,154 ms for the merge join it used to pick (-53%).
The estimate now comes from estimate_num_groups() on the clauses
estimate_multivariate_bucketsize() hands back, so bucket size and output
rows are built from the same estimator. SEMI/ANTI joins are
deliberately excluded: their probe charge is already scaled by
inner_scan_frac, and repricing it regressed a merge-semi-join query of
the workload by 27%.
0002: compute_semi_anti_join_factors() is also called for any join whose
inner side is provably unique -- plain inner joins and equally
LEFT/RIGHT/FULL joins -- but it asks clauselist_selectivity() the
semi-join question with the actual join's SpecialJoinInfo; eqjoinsel()
switches on sjinfo->jointype, so it answers with the pairwise selectivity
(1e-5) instead of the fraction of outer rows that find a match (1.0).
A 1.2M-row outer joined to a 100k unique inner then got hashjointuples =
12 in the same EXPLAIN node that prints rows = 1,200,418 -- cost and rows
contradicting each other by five orders of magnitude on one node. Fixed
by asking with a SEMI sjinfo and charging the output on the joinrel row
estimate; on the motivating query the corrected costing makes the planner
choose the merge join that measures 7% faster (986.9 ms vs 1,056.8 ms,
single shard, serial, median of 3).
Both changes affect plan choice for their shapes, so no backpatch is
planned. make check passes with the expected-file updates included; a
four-arm run of the workload with and without the series
shows no regression on the mixed workload. Three independent runs of
that harness (5 threads / 600 s, native plans, default GUCs) put both
arms inside the +/-2% run-to-run noise band every time:
+1.0% / +0.5%, -1.3% / -0.2%, and +0.9% on the second cluster.
One scope note to be clear about what the series does and does not
change: our harness plans shard tasks with parallel workers enabled,
and under parallel costing the two join types stay within 1.5% of each
other on the motivating query -- the parallel prices are accurate at
idle, and the merge join's runtime advantage there comes from cache
behavior under concurrent load, which the cost model does not observe.
Planning the same tasks serially lets 0002 choose the merge join
natively. We are not proposing any costing change for the parallel
case.
Test matrix on the workload's analytical queries: with
cpu_operator_cost reverted to its default, the default plans for two
other join-heavy queries were measurably slower than the alternatives
selected by the corrected model; the motivating query was unchanged
(single hash clause, correction does not apply).
Thanks,
He Kuang
final_cost_hashjoin() needs to know how many inner rows share a hash key,
and prices a probe with that number. When the hash key has several
columns, the per-clause loop answers a different question: it estimates
each column separately, keeps the smallest fraction, and therefore divides
by the largest single-column ndistinct. A bucket is selected by the whole
compound key, so under the independence assumption that
calc_joinrel_size_estimate() already makes about this very join, there are
inner_rows / (nd1 * nd2 * ...) rows in it. The same cost table therefore
believes two contradictory things: output rows multiply the selectivities,
bucket size divides only by the largest one.
The cost matters because the probe term scales with the bucket: with 100
distinct values in each of two key columns, the per-clause estimate prices
every probe against a bucket of 10,000 rows, which the planner usually
cannot afford, so it sorts both inputs instead.
Commit 6bb6a62f3 added estimate_multivariate_bucketsize(), which answers
from a multivariate ndistinct statistics object when one exists; that
function is left alone. The clauses it does not answer -- any table
without such an object, which is the common case -- are estimated here
instead, with estimate_num_groups(): the same estimator the row count of
this join is built on, so bucket size and output size can no longer
disagree; and unlike a bare product it bounds the result by the number of
input rows.
The correction is deliberately not applied to semi or anti joins, in
either direction. On those paths the probe charge is already scaled by
inner_scan_frac, which describes the same duplicate factor, so the bucket
fraction is not what the executor pays; re-pricing it changes no work, it
only moves the path down the same cost table. A join whose inner side is
merely unique is still corrected: its bucket really does hold about one
row per key.
---
src/backend/optimizer/path/costsize.c | 85 +++++++++++++++++++
src/test/regress/expected/eager_aggregate.out | 51 ++++-------
src/test/regress/expected/join.out | 29 +++----
src/test/regress/expected/stats_ext.out | 17 ++--
4 files changed, 124 insertions(+), 58 deletions(-)
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index 7bbddb8b..66c0ad9d 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -4434,6 +4434,57 @@ initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
workspace->inner_rows_total = inner_path_rows_total;
}
+/*
+ * hash_join_joint_ndistinct
+ * Estimate the joint ndistinct of the inner-side hash key columns of a
+ * multi-clause hash join.
+ *
+ * The per-clause loop in final_cost_hashjoin() keeps the smallest bucket
+ * fraction seen for any one clause, i.e. the largest ndistinct of any single
+ * key column. For a compound hash key that answers the wrong question: a
+ * bucket holds the rows that match *all* the clauses, and under the same
+ * independence assumption that calc_joinrel_size_estimate() already makes
+ * there are inner_rows / (nd1 * nd2 * ...) of them. estimate_num_groups()
+ * implements exactly that estimate, and unlike a bare product it bounds the
+ * result by the number of input rows.
+ *
+ * Returns -1.0, which no valid ndistinct can match, when the estimate cannot
+ * be formed: fewer than two clauses, a clause whose inner-side operand is
+ * not a plain Var of the inner relation, or a non-OpExpr clause.
+ */
+static double
+hash_join_joint_ndistinct(PlannerInfo *root, RelOptInfo *innerrel,
+ List *hashclauses)
+{
+ List *exprs = NIL;
+ ListCell *lc;
+
+ if (list_length(hashclauses) < 2)
+ return -1.0;
+
+ foreach(lc, hashclauses)
+ {
+ RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
+ Node *expr;
+
+ if (!IsA(rinfo->clause, OpExpr))
+ return -1.0;
+
+ if (bms_is_subset(rinfo->right_relids, innerrel->relids))
+ expr = get_rightop((OpExpr *) rinfo->clause);
+ else
+ expr = get_leftop((OpExpr *) rinfo->clause);
+
+ if (expr == NULL || !IsA(expr, Var) ||
+ !bms_is_member(((Var *) expr)->varno, innerrel->relids))
+ return -1.0;
+
+ exprs = lappend(exprs, expr);
+ }
+
+ return estimate_num_groups(root, exprs, innerrel->tuples, NULL, NULL);
+}
+
/*
* final_cost_hashjoin
* Final estimate of the cost and result size of a hashjoin path.
@@ -4468,6 +4519,7 @@ final_cost_hashjoin(PlannerInfo *root, HashPath *path,
double virtualbuckets;
Selectivity innerbucketsize;
Selectivity innermcvfreq;
+ double joint_ndistinct;
ListCell *hcl;
/* Set the number of disabled nodes. */
@@ -4583,6 +4635,39 @@ final_cost_hashjoin(PlannerInfo *root, HashPath *path,
if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq)
innermcvfreq = thismcvfreq;
}
+ /*
+ * Having more than one hash clause means the bucket is selected by the
+ * whole compound key, so the duplicate factor is the joint ndistinct,
+ * not the largest single-column one. Take whichever fraction is
+ * smaller; extended statistics, when they exist, have already had
+ * their say and only the clauses they did not cover are left here.
+ *
+ * Only for joins that look at the whole bucket, though. Semi and
+ * anti joins, in either direction, stop at the first match, and the
+ * probe charge below already says so through inner_scan_frac, so the
+ * bucket fraction is not what the executor pays for there;
+ * re-pricing it would not describe cheaper work, it would only move
+ * the path down the same cost table. A join whose inner side is
+ * merely unique still has to look
+ * at its bucket until the first row passes the join filter, and that
+ * bucket really does hold about one row per key, so the correction is
+ * applied there.
+ */
+ if (path->jpath.jointype == JOIN_SEMI ||
+ path->jpath.jointype == JOIN_ANTI ||
+ path->jpath.jointype == JOIN_RIGHT_SEMI ||
+ path->jpath.jointype == JOIN_RIGHT_ANTI)
+ joint_ndistinct = -1.0;
+ else
+ joint_ndistinct = hash_join_joint_ndistinct(root, inner_path->parent,
+ otherclauses);
+ if (joint_ndistinct > 0.0)
+ {
+ Selectivity joint_bucketsize = 1.0 / joint_ndistinct;
+
+ if (innerbucketsize > joint_bucketsize)
+ innerbucketsize = joint_bucketsize;
+ }
}
/*
diff --git a/src/test/regress/expected/eager_aggregate.out b/src/test/regress/expected/eager_aggregate.out
index bdda7da6..af691d52 100644
--- a/src/test/regress/expected/eager_aggregate.out
+++ b/src/test/regress/expected/eager_aggregate.out
@@ -1209,8 +1209,8 @@ SELECT t1.x, sum(t2.y)
LEFT JOIN eager_agg_tab1 t2 ON t1.x = t2.x AND t1.y = t2.y
JOIN eager_agg_tab1 t3 ON t1.x = t3.x AND COALESCE(t2.y, 0) < t3.y
GROUP BY t1.x ORDER BY t1.x;
- QUERY PLAN
----------------------------------------------------------------------------------------
+ QUERY PLAN
+--------------------------------------------------------------------------------------
Merge Append
Sort Key: t1.x
-> Finalize GroupAggregate
@@ -1223,21 +1223,16 @@ GROUP BY t1.x ORDER BY t1.x;
-> Partial GroupAggregate
Output: t1.x, t2.y, PARTIAL sum(t2.y)
Group Key: t1.x, t2.y
- -> Incremental Sort
+ -> Sort
Output: t1.x, t2.y
Sort Key: t1.x, t2.y
- Presorted Key: t1.x
- -> Merge Left Join
+ -> Hash Left Join
Output: t1.x, t2.y
- Merge Cond: ((t1.x = t2.x) AND (t1.y = t2.y))
- -> Sort
+ Hash Cond: ((t1.x = t2.x) AND (t1.y = t2.y))
+ -> Seq Scan on public.eager_agg_tab1_p1 t1
Output: t1.x, t1.y
- Sort Key: t1.x, t1.y
- -> Seq Scan on public.eager_agg_tab1_p1 t1
- Output: t1.x, t1.y
- -> Sort
+ -> Hash
Output: t2.y, t2.x
- Sort Key: t2.x, t2.y
-> Seq Scan on public.eager_agg_tab1_p1 t2
Output: t2.y, t2.x
-> Sort
@@ -1255,21 +1250,16 @@ GROUP BY t1.x ORDER BY t1.x;
-> Partial GroupAggregate
Output: t1_1.x, t2_1.y, PARTIAL sum(t2_1.y)
Group Key: t1_1.x, t2_1.y
- -> Incremental Sort
+ -> Sort
Output: t1_1.x, t2_1.y
Sort Key: t1_1.x, t2_1.y
- Presorted Key: t1_1.x
- -> Merge Left Join
+ -> Hash Left Join
Output: t1_1.x, t2_1.y
- Merge Cond: ((t1_1.x = t2_1.x) AND (t1_1.y = t2_1.y))
- -> Sort
+ Hash Cond: ((t1_1.x = t2_1.x) AND (t1_1.y = t2_1.y))
+ -> Seq Scan on public.eager_agg_tab1_p2 t1_1
Output: t1_1.x, t1_1.y
- Sort Key: t1_1.x, t1_1.y
- -> Seq Scan on public.eager_agg_tab1_p2 t1_1
- Output: t1_1.x, t1_1.y
- -> Sort
+ -> Hash
Output: t2_1.y, t2_1.x
- Sort Key: t2_1.x, t2_1.y
-> Seq Scan on public.eager_agg_tab1_p2 t2_1
Output: t2_1.y, t2_1.x
-> Sort
@@ -1287,21 +1277,16 @@ GROUP BY t1.x ORDER BY t1.x;
-> Partial GroupAggregate
Output: t1_2.x, t2_2.y, PARTIAL sum(t2_2.y)
Group Key: t1_2.x, t2_2.y
- -> Incremental Sort
+ -> Sort
Output: t1_2.x, t2_2.y
Sort Key: t1_2.x, t2_2.y
- Presorted Key: t1_2.x
- -> Merge Left Join
+ -> Hash Left Join
Output: t1_2.x, t2_2.y
- Merge Cond: ((t1_2.x = t2_2.x) AND (t1_2.y = t2_2.y))
- -> Sort
+ Hash Cond: ((t1_2.x = t2_2.x) AND (t1_2.y = t2_2.y))
+ -> Seq Scan on public.eager_agg_tab1_p3 t1_2
Output: t1_2.x, t1_2.y
- Sort Key: t1_2.x, t1_2.y
- -> Seq Scan on public.eager_agg_tab1_p3 t1_2
- Output: t1_2.x, t1_2.y
- -> Sort
+ -> Hash
Output: t2_2.y, t2_2.x
- Sort Key: t2_2.x, t2_2.y
-> Seq Scan on public.eager_agg_tab1_p3 t2_2
Output: t2_2.y, t2_2.x
-> Sort
@@ -1309,7 +1294,7 @@ GROUP BY t1.x ORDER BY t1.x;
Sort Key: t3_2.x
-> Seq Scan on public.eager_agg_tab1_p3 t3_2
Output: t3_2.x, t3_2.y
-(98 rows)
+(83 rows)
SELECT t1.x, sum(t2.y)
FROM eager_agg_tab1 t1
diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out
index 7773852e..9aecac74 100644
--- a/src/test/regress/expected/join.out
+++ b/src/test/regress/expected/join.out
@@ -2756,17 +2756,16 @@ select * from
j1_tbl full join
(select * from j2_tbl order by j2_tbl.i desc, j2_tbl.k asc) j2_tbl
on j1_tbl.i = j2_tbl.i and j1_tbl.i = j2_tbl.k;
- QUERY PLAN
------------------------------------------------------------------
- Merge Full Join
- Merge Cond: ((j2_tbl.i = j1_tbl.i) AND (j2_tbl.k = j1_tbl.i))
+ QUERY PLAN
+----------------------------------------------------------------
+ Hash Full Join
+ Hash Cond: ((j2_tbl.i = j1_tbl.i) AND (j2_tbl.k = j1_tbl.i))
-> Sort
Sort Key: j2_tbl.i DESC, j2_tbl.k
-> Seq Scan on j2_tbl
- -> Sort
- Sort Key: j1_tbl.i DESC
+ -> Hash
-> Seq Scan on j1_tbl
-(8 rows)
+(7 rows)
select * from
j1_tbl full join
@@ -2776,23 +2775,23 @@ select * from
---+---+-------+---+----
| | | | 0
| | | |
- | 0 | zero | |
- | | null | |
- 8 | 8 | eight | |
- 7 | 7 | seven | |
- 6 | 6 | six | |
| | | 5 | -5
| | | 5 | -5
- 5 | 0 | five | |
- 4 | 1 | four | |
| | | 3 | -3
- 3 | 2 | three | |
2 | 3 | two | 2 | 2
| | | 2 | 4
| | | 1 | -1
| | | 0 |
+ 3 | 2 | three | |
+ 4 | 1 | four | |
1 | 4 | one | |
0 | | zero | |
+ 7 | 7 | seven | |
+ 8 | 8 | eight | |
+ 6 | 6 | six | |
+ 5 | 0 | five | |
+ | | null | |
+ | 0 | zero | |
(19 rows)
--
diff --git a/src/test/regress/expected/stats_ext.out b/src/test/regress/expected/stats_ext.out
index 5b4bcfae..f2bb0d75 100644
--- a/src/test/regress/expected/stats_ext.out
+++ b/src/test/regress/expected/stats_ext.out
@@ -3661,17 +3661,14 @@ ANALYZE sb_1, sb_2;
-- bucket size is quite big because there are possibly many correlations.
EXPLAIN (COSTS OFF) -- Choose merge join
SELECT * FROM sb_1 a, sb_2 b WHERE a.x = b.x AND a.y = b.y AND a.z = b.z;
- QUERY PLAN
--------------------------------------------------------------
- Merge Join
- Merge Cond: ((a.z = b.z) AND (a.x = b.x) AND (a.y = b.y))
- -> Sort
- Sort Key: a.z, a.x, a.y
- -> Seq Scan on sb_1 a
- -> Sort
- Sort Key: b.z, b.x, b.y
+ QUERY PLAN
+------------------------------------------------------------
+ Hash Join
+ Hash Cond: ((a.x = b.x) AND (a.y = b.y) AND (a.z = b.z))
+ -> Seq Scan on sb_1 a
+ -> Hash
-> Seq Scan on sb_2 b
-(8 rows)
+(5 rows)
-- The ndistinct extended statistics on (x, y, z) provides more reliable value
-- of bucket size.
--
2.43.0
compute_semi_anti_join_factors() is called for any join whose inner side
is provably unique -- a plain inner join, and equally a LEFT, RIGHT or
FULL join -- because the executor stops at the first match and the
fraction of outer rows that find a match is then what the cost model
wants, just as for a semi join. It asks clauselist_selectivity() for the
semi-join selectivity, but hands it the SpecialJoinInfo of the actual
join, and eqjoinsel() decides what it is being asked from
sjinfo->jointype plus min_lefthand/righthand -- not from the jointype
argument alone. With a non-SEMI sjinfo the answer is the ordinary
equality selectivity: the fraction of the Cartesian product that matches,
not the fraction of outer rows that find a match.
For a unique inner side the two differ by the size of the inner relation.
An outer relation of 1,200,000 rows joined to a 100,000-row unique inner
relation gets outer_match_frac = 1e-5 instead of 1 (taking the outer
key's ndistinct to be no larger than the inner's, as holds for a
foreign-key reference). The join's row estimate is fine -- EXPLAIN
prints rows = 1,200,418 for this node -- but the cost side of the same
node charges the per-output-tuple CPU work on hashjointuples = 12,
pricing 1,200,000 output tuples as if there were 12: a
five-orders-of-magnitude understatement of that term, enough to hide a
merge join that is cheaper to execute.
Ask with a SpecialJoinInfo that describes the same join as a SEMI join.
There is a second half to this. outer_matched_rows is exact for a real
SEMI or ANTI join, where it *is* the output. For a plain inner join it is
not: what leaves the join is the joinrel row estimate, which is what every
other node in the plan is built on. The two agree when the semi-join
question is asked correctly and there is a single hash clause; they need
not agree otherwise, because eqjoinsel_semi() takes the minimum over the
clauses while calc_joinrel_size_estimate() multiplies them. So charge the
output tuples on the joinrel row count for inner joins. For the outer
join types keep charging outer_matched_rows: the fix above already
corrects that number for them -- their outer_match_frac was subject to
the same bug -- but what a LEFT or FULL join emits on top of the matched
rows is a different question, deliberately left alone here.
---
src/backend/optimizer/path/costsize.c | 66 +++++++++++++++++++++++----
src/test/regress/expected/join.out | 23 +++++-----
2 files changed, 69 insertions(+), 20 deletions(-)
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index 66c0ad9d..ceb7bf88 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -4435,9 +4435,8 @@ initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
}
/*
- * hash_join_joint_ndistinct
- * Estimate the joint ndistinct of the inner-side hash key columns of a
- * multi-clause hash join.
+ * Estimate the number of distinct values of the inner-side hash key, taken as
+ * a whole, for a multi-clause hash join.
*
* The per-clause loop in final_cost_hashjoin() keeps the smallest bucket
* fraction seen for any one clause, i.e. the largest ndistinct of any single
@@ -4448,9 +4447,8 @@ initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
* implements exactly that estimate, and unlike a bare product it bounds the
* result by the number of input rows.
*
- * Returns -1.0, which no valid ndistinct can match, when the estimate cannot
- * be formed: fewer than two clauses, a clause whose inner-side operand is
- * not a plain Var of the inner relation, or a non-OpExpr clause.
+ * Returns -1.0 when there is nothing to add: fewer than two clauses, a key
+ * that is not a plain Var of the inner relation, or a non-OpExpr clause.
*/
static double
hash_join_joint_ndistinct(PlannerInfo *root, RelOptInfo *innerrel,
@@ -4794,8 +4792,37 @@ final_cost_hashjoin(PlannerInfo *root, HashPath *path,
(1.0 - extra->semifactors.outer_match_frac));
else if (path->jpath.jointype == JOIN_ANTI)
hashjointuples = outer_path_rows - outer_matched_rows;
- else if (path->jpath.jointype == JOIN_SEMI || extra->inner_unique)
+ else if (path->jpath.jointype == JOIN_SEMI)
hashjointuples = outer_matched_rows;
+ else if (extra->inner_unique)
+ {
+ if (path->jpath.jointype == JOIN_INNER)
+ {
+ /*
+ * A plain inner join with a provably unique inner side stops at the
+ * first match, but the tuples it emits are the join's output, i.e.
+ * the joinrel row estimate that every other node in the plan is
+ * built on. outer_matched_rows agrees with that when the semi-join
+ * question is asked correctly and there is a single hash clause; it
+ * need not agree otherwise, since eqjoinsel_semi() takes the
+ * minimum over the clauses while the join size estimate
+ * multiplies them. Charge the join's own row estimate, so the
+ * output count priced here is the same one the rest of the plan
+ * is built on.
+ */
+ hashjointuples = path->jpath.path.rows;
+ }
+ else
+ {
+ /*
+ * Outer joins: what they emit is not the matched outer rows
+ * either (a FULL join also emits unmatched inner rows), but
+ * correcting that is a separate question, so keep the old
+ * estimate.
+ */
+ hashjointuples = outer_matched_rows;
+ }
+ }
else
hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
@@ -5457,6 +5484,8 @@ compute_semi_anti_join_factors(PlannerInfo *root,
Selectivity nselec;
Selectivity avgmatch;
SpecialJoinInfo norm_sjinfo;
+ SpecialJoinInfo semi_sjinfo;
+ SpecialJoinInfo *sel_sjinfo;
List *joinquals;
ListCell *l;
@@ -5483,14 +5512,35 @@ compute_semi_anti_join_factors(PlannerInfo *root,
/*
* Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
+ *
+ * eqjoinsel() decides whether it is being asked a semi-join question from
+ * sjinfo->jointype and sjinfo->min_lefthand/righthand, not from its
+ * jointype argument alone. The caller can be any join whose inner side
+ * is proven unique -- a plain inner join, or a LEFT, RIGHT or FULL join
+ * (see add_paths_to_joinrel) -- and the sjinfo we get describes that
+ * join, not a semi join, so the answer we get back is the ordinary
+ * equality selectivity -- the fraction of the Cartesian product that
+ * matches, not the fraction of outer rows that find a match. Build a
+ * SpecialJoinInfo that describes the same join as a SEMI join before
+ * asking, so that jselec means what the rest of this function and its
+ * callers assume it means.
*/
+ sel_sjinfo = sjinfo;
+ if (jointype != JOIN_SEMI && jointype != JOIN_ANTI &&
+ jointype != JOIN_RIGHT_SEMI && jointype != JOIN_RIGHT_ANTI)
+ {
+ init_dummy_sjinfo(&semi_sjinfo, outerrel->relids, innerrel->relids);
+ semi_sjinfo.jointype = JOIN_SEMI;
+ sel_sjinfo = &semi_sjinfo;
+ }
+
jselec = clauselist_selectivity(root,
joinquals,
0,
(jointype == JOIN_ANTI ||
jointype == JOIN_RIGHT_ANTI) ?
JOIN_ANTI : JOIN_SEMI,
- sjinfo);
+ sel_sjinfo);
/*
* Also get the normal inner-join selectivity of the join clauses, to
diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out
index 9aecac74..f42e54f4 100644
--- a/src/test/regress/expected/join.out
+++ b/src/test/regress/expected/join.out
@@ -12379,15 +12379,15 @@ select * from fkest f1
QUERY PLAN
-----------------------------------------------------
Hash Join
- Hash Cond: ((f2.x = f1.x) AND (f2.x10b = f1.x10))
+ Hash Cond: ((f1.x = f2.x) AND (f1.x10 = f2.x10b))
-> Hash Join
- Hash Cond: (f3.x = f2.x)
+ Hash Cond: (f3.x = f1.x)
-> Seq Scan on fkest f3
-> Hash
- -> Seq Scan on fkest f2
+ -> Seq Scan on fkest f1
Filter: (x100 = 2)
-> Hash
- -> Seq Scan on fkest f1
+ -> Seq Scan on fkest f2
Filter: (x100 = 2)
(11 rows)
@@ -12479,15 +12479,14 @@ select * from j1 inner join j3 on j1.id = j3.id;
-----------------------------------
Hash Join
Output: j1.id, j3.id
- Inner Unique: true
- Hash Cond: (j3.id = j1.id)
- -> Seq Scan on public.j3
- Output: j3.id
- -> Hash
+ Hash Cond: (j1.id = j3.id)
+ -> Seq Scan on public.j1
Output: j1.id
- -> Seq Scan on public.j1
- Output: j1.id
-(10 rows)
+ -> Hash
+ Output: j3.id
+ -> Seq Scan on public.j3
+ Output: j3.id
+(9 rows)
-- ensure left join is marked as unique
explain (verbose, costs off)
--
2.43.0
On 11/11/2026 13:12, He Kuang wrote:
0001: Multi-column hash keys estimate the bucket size from the largest
single-column ndistinct (the minimum over per-clause fractions), while
the output row count of the same join is estimated under the
independence assumption that calc_joinrel_size_estimate() already makes.
The same cost table therefore holds two contradictory beliefs about one
join: on a 1M x 1M three-column join with 100 distinct values per column
(one row per bucket), hash join is priced at 166,622,722 and never
chosen; with the corrected bucket size it costs 282,717 and runs in
1,946 ms versus 4,154 ms for the merge join it used to pick (-53%).
The estimate now comes from estimate_num_groups() on the clauses
estimate_multivariate_bucketsize() hands back, so bucket size and output
rows are built from the same estimator. SEMI/ANTI joins are
deliberately excluded: their probe charge is already scaled by
inner_scan_frac, and repricing it regressed a merge-semi-join query of
the workload by 27%.
I think it's worth looking at the earlier discussion on this list. 0001 is
essentially the approach we discussed previously [1]/messages/by-id/1de52b5f-e4a6-5729-eeef-51d524534665@enterprisedb.com, which concluded with
6bb6a62f3 - only using the product where the extended stats backed it up. If you
have any new arguments for re-visiting that, please put them forward.
[1]: /messages/by-id/1de52b5f-e4a6-5729-eeef-51d524534665@enterprisedb.com
/messages/by-id/1de52b5f-e4a6-5729-eeef-51d524534665@enterprisedb.com
--
regards, Andrei Lepikhov,
pgEdge
Show quoted text
On Nov 11, 2026, Andrei Lepikhov wrote:
I think it's worth looking at the earlier discussion on this list.
0001 is essentially the approach we discussed previously [1], which
concluded with 6bb6a62f3 - only using the product where the extended
stats backed it up. If you have any new arguments for re-visiting
that, please put them forward.Thanks for the reply. The PATCH 1/2 email does discuss 6bb6a62f3
directly; its commit message says:Commit 6bb6a62f3 added estimate_multivariate_bucketsize(), which
answers from a multivariate ndistinct statistics object when one
exists; that function is left alone. The clauses it does not
answer -- any table without such an object, which is the common
case -- are estimated here instead, with estimate_num_groups()and the code comment in the patch repeats the same point ("extended
statistics, when they exist, have already had their say ..."). But the
sentence that matters is yours: whether the series earns a re-visit of
that decision. Let me lay out the full picture.That thread started from the same symptom this series reports: with
several hash clauses, the per-clause loop divides by the largest
single-column ndistinct, hash join is priced out, and a slower merge
join wins. The bare product proposed there died on Tomas's objection
-- under correlation it prices buckets that do not exist -- and
6bb6a62f3 was the principled middle ground: use a better ndistinct
estimate, but only where extended statistics back it up. 0001 keeps
that stage intact and in priority. Mechanically, in
final_cost_hashjoin() the statistics estimator runs first and folds its
fraction into innerbucketsize; hash_join_joint_ndistinct() then sees
only the clauses it returns uncovered; and the final min() treats every
estimate, statistical or new alike, as a bound on the bucket, so the
new estimate can only shrink the result, never enlarge it. The gap it
fills is real: for the uncovered clauses -- tables without such
statistics, the common case -- the status quo is the per-clause
minimum, i.e. exactly the conservatism the thread began from.Since you ask for new arguments for re-visiting that remaining line,
here is what I have:1. Consistency within one join node. calc_joinrel_size_estimate()
already prices the output rows of this very join under the
independence assumption, while the per-clause loop prices the bucket
by the largest single-column ndistinct. The same cost table thus
holds two contradictory answers for the same hash key.
estimate_num_groups() is the estimator the row count already comes
from, so bucket and rows can no longer disagree: if independence is
wrong for the bucket, it is already wrong for the rows the planner
prints.2. It is not the bare product Tomas objected to. estimate_num_groups()
works from sampled per-column ndistinct, applies functional
dependencies when a statistics object covers the columns, and bounds
the result by the number of input rows. The stats_ext.out case this
patch must update shows the difference: the hash side there (sb_2)
has effectively independent keys (coprime moduli 49/51/73), and the
input-row bound recovers the true joint ndistinct (~10^4) that the
per-clause estimate cannot see. The old estimate overpriced that
bucket about 137x (1/73 vs 1e-4), so the plan flip says the old
estimate was wrong, not that the new one is optimistic. (The stale
"-- Choose merge join" comments in that test will be fixed in v2.)3. SEMI/ANTI joins are excluded, which the 2023 proposal did not do.
Their probe charge is already scaled by inner_scan_frac, which
describes the same duplicate factor, so re-pricing the bucket
changes no work; it only moves such paths down the same cost table.
Excluding them was forced by measurement: keeping them regressed a
merge-semi-join query in the workload by 27%.On the motivating query the corrected bucket estimate turns a
never-chosen hash join (cost 166,622,722) into the winning plan (cost
282,717; 1,946 ms vs 4,154 ms for the merge join it used to pick), and
runs with and without the series stayed within the +/-2% run-to-run
noise band.The exposure I do not have a principled answer for remains an inner
side with fully correlated key columns and no statistics (the sb_1
construction, x = y = z), where the estimate is optimistic by roughly
the per-column product. My position is that consistency with the rows
estimator is still the better bet there, because the planner already
takes that bet for the join's row count. But if you see a shape where
this clearly misleads plan choice, I will gladly add it as a test case
and either bound or document the behavior.Thanks,
He Kuang