Repository navigation
Fix INNER JOIN cardinality underestimation in join reorder optimizer - #109261
JingYanchao wants to merge 14 commits into
Conversation
|
Workflow [PR], commit [6c015c7] Summary: ❌
AI ReviewSummaryThe current head fixes the earlier mixed-statistics and transitive-predicate regressions, but two correctness gaps remain in the new star-schema guard machinery. The guard is still asymmetric in PR Metadata💡 Exact replacement:
Findings
Final VerdictStatus: |
|
Heads-up on the current state of this PR — the implementation has diverged from what was reviewed, and CI is red. The approval is stale. The approval here was given on commit if (join_kind == JoinKind::Inner)
joined_rows = std::max(joined_rows, std::max(lhs, rhs));That is exactly the change described in the PR body ("adds a cardinality floor for INNER JOINs: the result cannot be smaller than CI is red because of this change. Three deterministic
These tests deliberately pin an optimal plan (e.g. @vdimir, since this touches Also, the PR description should be updated to describe the swap-guard approach if that is the one being kept. |
|
Refreshed this branch against current Note the CI report link in my previous comment is now stale (it points at The design question is still open and I did not touch it: I have not regenerated the three |
|
Fresh CI on
So the recent join-reorder work (DPsub chained-outer-join fix, I have not regenerated the three (The |
The previous commit regenerated this reference from the intermediate NDV-cap implementation, which was then reverted back to the swap guard in `optimizeJoin.cpp`, so the reference no longer matched the plans the final code produces. Regenerated from the current branch; output is deterministic across runs. The plan change is the swap guard's intended effect: the statistics-less composite subtree stays on the probe side instead of being swapped to the hash-join build side. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109261&sha=6458e59d985da41a64da4c5237711397aa8d300e&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Fable 5 <[email protected]>
|
Update after the author's new commits ( I pushed @vdimir the remaining question is still yours: the guard changes three pinned |
`RelationStats::column_stats` is a per-column map, so checking `entry->left->column_stats.empty()` was too coarse: a composite subtree `(fact JOIN dim_a)` where only `dim_a` carries statistics has a non-empty map, yet `getColumnStats` still falls back to the `estimated_rows` NDV proxy for the fact table's next join key, underestimating the composite exactly as in the stats-less case — and the guard was wrongly skipped, swapping the fact subtree to the hash-join build side. Check the equi-join keys of this join step that belong to the left subtree instead: the guard now applies iff none of them have column statistics, mirroring the proxy-fallback condition in `getColumnStats`. Add `04609_join_reorder_star_schema_mixed_stats` where only one dimension has statistics (verified to fail without the guard). No pinned join-order plans change: all `03960_join_order_dphyp_*`, `03733_join_order_dp`, `03734`/`03738`/`03835`/`04050` join-order tests and `04498` pass unchanged. ClickHouse#109261 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
… left subtree The previous per-step check (`anyLeftJoinKeyHasColumnStats`) was still too weak: `computeSelectivity` takes the minimum across equality predicates, so one proxy-based key dominates a multi-key join even when another key has statistics; and an earlier proxy-based join inside the left composite leaves `estimated_rows` underestimated on later steps even when the later step's keys do have statistics. The star-schema swap guard now precomputes, bottom-up over the post-order join sequence, whether each subtree's cardinality estimate is stats-based: true iff every equi-join key at every join step inside the subtree has column statistics, mirroring the per-key lookup and `estimated_rows` fallback of `getColumnStats`. The pre-pass runs before the main loop because that loop moves `join_operator` out of the entries. Adds `04611_join_reorder_star_schema_partial_key_stats`: statistics only on `fact.key_b` (the key of the second join), so the composite `(fact JOIN dim_a ON key_a)` is already underestimated when the second join's key has statistics; a current-step-only check would still swap the fact subtree to the hash-join build side. All 20 `03960_join_order_dphyp_*` tests plus `03733`, `03734`, `03738`, the `03835*` family, `04050`, `04498`, and `04609` pass unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
| Expression (Post Join Actions) | ||
| Join (JOIN FillRightFirst) | ||
| Expression (Left Pre Join Actions) | ||
| Expression (Change column names to column identifiers) |
There was a problem hiding this comment.
I also noted that materialize_statistics_on_insert was not enabled for _dphyp_ tests, so statistics were not used there, enabling it in https://github.com/ClickHouse/ClickHouse/pull/107637/changes
Probably we should do so in this PR and see how it changes referece
There was a problem hiding this comment.
Done in 7b31feb: 03960_join_order_dphyp_basic, _cycle and _transitive_predicates now pin materialize_statistics_on_insert = 1 (they already declared uniq statistics and set use_statistics = 1, so previously every NDV lookup silently fell back to the estimated_rows proxy), and the references are regenerated from the resulting plans.
What changed: with real statistics the pinned plans differ both from the old references and from the swap-guard-under-proxy plans — e.g. in _transitive_predicates the fact table now consistently lands on the probe side of the outermost join, and in _basic/_cycle the build/probe sides of the inner steps shift. Only EXPLAIN plan lines changed; the result-check hashes and row counts are identical, and the output is deterministic across runs. The swap guard itself does not fire on these tests anymore (their estimates are now genuinely stats-based), so the pinned plans reflect the plain cost model on real NDVs, which should also keep them stable against your #107637.
…der optimizer The star-schema swap guard needs to know whether a composite subtree's cardinality estimate was derived from real column statistics. Deriving it in `chooseJoinOrder` from the final join tree missed one estimator path: `computeSelectivity` also scans every column-equivalence class spanning the two sides and uses `getColumnStats` on all of its members, and `cleanupJoinPredicates` may remove or synthesize predicates before `chooseJoinOrder` runs, so a proxy-based lookup could disappear from the step's expression while still dominating the class-wide max NDV. Record the flag in `DPJoinEntry::estimate_is_stats_based` instead, filled by `optimizeJoinOrder` right after the solver and before `cleanupJoinPredicates`, mirroring every NDV lookup `computeSelectivity` makes: both sides of every equi-predicate attached to a step (including `residual_filter`) and every member of every spanning equivalence class. The guard in `chooseJoinOrder` now just reads the flag, and the `stepJoinKeysHaveColumnStats` helper plus the pre-pass are removed. Adds `04621_join_reorder_star_schema_transitive_stats`: with `enable_join_transitive_predicates` and statistics only on the dimension keys, the stats-less `fact.key` poisons the composite estimate through the equivalence class, and the fact table must stay on the probe side. Co-Authored-By: Claude Fable 5 <[email protected]>
Per review: the `03960_join_order_dphyp_basic`, `_cycle` and `_transitive_predicates` tests declared `uniq` statistics and set `use_statistics = 1` but pinned `materialize_statistics_on_insert = 0`, so no statistics were ever built and every NDV estimate fell back to the `estimated_rows` proxy. Pin the setting to 1 instead, so the declared statistics are materialized and the pinned plans are driven by real NDV estimates. References are regenerated for the resulting plans; the result-check hashes and row counts are unchanged, and the output is deterministic across runs. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Pushed two commits addressing today's review feedback:
All 34 pinned join-order plan tests pass locally and deterministically. The two CI failures on the previous head are unrelated to this PR:
|
|
Investigated the arm_binary 04365 failure (sha e532419, report linked above). It is a distinct manifestation from the coverage one, so #110716 does not cover it. Two separate signatures over the last 30 days:
So #110716 (in progress) is the coverage fix and does not address this. The arm_binary timing race needs a separate fix that makes the cancellation observation reliable without weakening the assertion (it must still detect a real cancellation). I will open that separate PR and link it here. |
|
Separate PR for the arm_binary flakiness: #111157. Root cause is a timing gap in the test's own Reproduced both directions locally (extracting the actual |
…wins the competition `joinStepEstimateIsStatsBased` treated any NDV lookup that fell back to the `estimated_rows` proxy as poisoning the subtree estimate, but `computeSelectivity` uses `1 / max(lhs_ndv, rhs_ndv)` per equality and then takes the minimum across predicates and the class-wide maximum inside each equivalence class — so a proxy fallback only affects the estimate when its value actually wins that competition. The helper now tracks the largest stats-backed and largest proxy-backed NDV over every mirrored lookup of the step and marks the step proxy-based only when the proxy value strictly exceeds every stats-backed one. A stats-less small dimension joined on a fact key with a real `uniq` statistic no longer disables the beneficial build/probe swap for the composite. Regression test `04622_join_reorder_star_schema_dominant_stats`: statistics only on the unique `fact.key_a`; the composite `(fact JOIN dim_a)` estimate (~50 rows) is driven by the real fact NDV, so the swap must still move the composite to the build side against the larger `dim_b`. Verified the previous code keeps `fact` on the probe side (test fails) while all 33 pinned join-order plan tests pass unchanged with the new code.
| /// estimate is proxy-based is joined against a single smaller table. It | ||
| /// only gates the physical build/probe-side choice and never changes | ||
| /// cardinality estimates, so the enumerated join order is unaffected. | ||
| if (swap_on_sizes && !optimization_settings.join_swap_table.has_value() |
There was a problem hiding this comment.
swap_on_sizes is only suppressed when the poisoned composite happens to be entry->left, but the optimizer's left/right orientation is not semantic. In dphyp, the final pair is stored as (csg, cmp), so the same star join can reach this code as left = dim_b, right = (fact JOIN dim_a) when the larger dimension has the smallest relation id.
In that shape lhs_estimation < rhs_estimation is false (100 < 50), so flip_join stays false and the underestimated fact subtree remains on the build side without ever hitting this guard. A focused regression with query_plan_optimize_join_order_algorithm = 'dphyp' and the relations ordered dim_b, fact, dim_a should still reproduce the original bad plan. The check needs to be symmetric around the side that would end up on the build side, not only entry->left.
| return true; | ||
| } | ||
|
|
||
| const DPJoinEntry * child = nullptr; |
There was a problem hiding this comment.
This no longer mirrors getColumnStats for multi-relation expression keys. getColumnStats looks up dp_table[rels] for the exact source-relation set of the key, but here any multi-relation key is charged to whichever immediate child merely contains that set.
That diverges as soon as a predicate side uses a proper subset of a larger child, e.g. A.x = B.y + C.z after (B JOIN C) has already been joined with D: the cost model still uses dp_table[{B,C}] for B.y + C.z, while this helper falls back to {B,C,D}'s column_stats / estimated_rows instead. The proxy-vs-stats winner can change in both directions, so estimate_is_stats_based can still suppress or allow later swaps for the wrong reason. This probably needs to be recorded while the DP entry is evaluated, when the exact rels lookup that drove computeSelectivity is still available, rather than reconstructed from the final tree.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 104/111 (93.69%) · Uncovered code |
|
Dear @alexey-milovidov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Resolved by #109454 If the problem persists for you, please reopen (and also provide a minimal reproducible example then please). |
Changelog category (leave one):
Changelog entry
Fixed the join reorder optimizer placing a large fact table on the hash-join build side in star-schema queries when column statistics are unavailable. A narrow guard now suppresses the build/probe swap when a statistics-less composite subtree that contains a base table larger than the other side is joined with a single smaller dimension table.
Analysis
The join reorder optimizer uses
1/max(NDV_left, NDV_right)as join selectivity. Without per-column NDV statistics,estimated_rowsof the table is used as a proxy for NDV. For a star schema query likefact JOIN dim_a ON dim_a.key = fact.key_a JOIN dim_b ON dim_b.key = fact.key_b, the selectivity offact JOIN dim_abecomes1/max(100000, 100) = 1/100000, producing a cardinality estimate of100000 * 100 / 100000 = 100rows — far below the actual ~100000 rows.This makes the optimizer believe the intermediate result is tiny (100 rows) compared to
dim_b(200 rows), so it swaps the join sides and puts the large fact table on the build side — exactly the wrong decision for a star-schema workload.Fix
A narrow swap guard in
chooseJoinOrder(optimizeJoin.cpp): do not swap build/probe sides when all of the following hold:DPJoinEntry::estimate_is_stats_based(markStatsBasedEstimatesinjoinOrder.cpp), filled for the chosen plan beforecleanupJoinPredicatesrewrites the predicates. It mirrors every NDV lookupcomputeSelectivitymakes: both sides of every equi-predicate attached to a step (including predicates routed toresidual_filter) and every member of every column-equivalence class spanning the two sides — so a proxy-based lookup on the transitive-predicate path is caught even when predicate cleanup removes it from the step's expression. Since the step selectivity is the minimum over contributions of1/max(ndv...), a proxy fallback only affects the estimate when its value actually wins that competition, so a step is marked proxy-based only when the largest proxy-backed NDV strictly exceeds every stats-backed one — a stats-less small dimension joined on a fact key with a realuniqstatistic does not poison the flag. The flag is recursive over the whole subtree because the underestimation of an earlier proxy-based join propagates upward,The guard only gates the physical build/probe-side choice and never changes cardinality estimates, so the enumerated join order is unaffected. When column statistics are available, the standard formula already produces reasonable estimates and the guard does not fire.
Regression tests:
04498_join_reorder_star_schema_cardinality(no statistics at all),04609_join_reorder_star_schema_mixed_stats(an unrelated dimension statistic must not disable the guard),04611_join_reorder_star_schema_partial_key_stats(a statistic on a later join key must not mask an earlier proxy-based join inside the composite),04621_join_reorder_star_schema_transitive_stats(withenable_join_transitive_predicates, a stats-less fact key reachable only through the equivalence class must not be masked by a stats-covered retained predicate),04622_join_reorder_star_schema_dominant_stats(a proxy lookup that loses the NDV competition to a real fact-key statistic must not fire the guard, so the beneficial swap of the correctly-estimated composite is kept).(An earlier revision of this PR implemented this as an unconditional
INNER JOINcardinality floor, and an intermediate revision as an NDV cap inestimateJoinCardinality; both changed cardinality estimates globally and were replaced by this narrower guard.)Per review, the
03960_join_order_dphyp_basic/_cycle/_transitive_predicatestests now pinmaterialize_statistics_on_insert = 1— they declareduniqstatistics and setuse_statistics = 1but never materialized the statistics, so their pinned plans were driven by theestimated_rowsNDV proxy. Their references are regenerated for plans driven by real NDV estimates (the swap guard does not fire on them anymore); result-check hashes and row counts are unchanged.Example of a star-schema query whose performance was poor because
lineorder(the fact table) was moved to the build side: