Skip to content

Revert "Revert "Join reordering: FK->PK heuristic for equi joins without NDV statistics"" - #121075

Merged
alexey-milovidov merged 11 commits into
masterfrom
revert-120923-revert-120176-join-order-fk-pk-heuristic
Oct 7, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
revert-120923-revert-120176-join-order-fk-pk-heuristic

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

Relands #120176 (reverted in #120923), this time with a fix for the regression that caused the revert.

The FK->PK heuristic is kept for equi joins where both sides have row estimates. The first reland attempt reproduced the original regression: iceberg_suite_tpch query 4 timed out again (https://s3.amazonaws.com/clickhouse-test-reports/PRs/121075/f19b8377064891f2ad800238a632f4fd6ab8703f/pr/performance_comparison_arm_release_master_head_6_6/report.html) and tpcds query 71 was 22 times slower. Both come from joins where one side has no row estimate, see #120921. For that case the behavior now matches the state before the heuristic:

  • estimateJoinCardinality returns unknown when either side is unknown, for every join kind. It used to return the known side, which produced 1-row estimates for large intermediates and made them the build side.
  • The cost (estimateJoinedRows) of a join with an unknown side is exactly the pre-heuristic cost: the selectivity from the NDV or row-count upper bound of the key (reported_value) times the row counts, with a missing one counted as 1 row. This keeps the order of joins where a key from a relation of known size (such as one sized from the hash table statistics cache) makes a join with a sub-join of unknown size cheap. A second attempt, which used the smaller side as the cost, still made iceberg_suite_tpch Q5 and Q9 47% and 16% slower (https://s3.amazonaws.com/clickhouse-test-reports/PRs/121075/0960a9375b9f531bc7b9ed8663169858deabb006/pr/performance_comparison_arm_release_master_head_3_6/report.html). 05331_join_order_one_side_unknown_rows pins the Q5 order.
  • DPJoinEntry::selectivity publishes the NDV-based selectivity again (a key without NDV statistics falls back to the row count of its relation, as on master), since EXPLAIN reports it as estimated (NDV).

As a result, 03708, 03734, 03836 and 03837 have the same references as on master again, while the plans of queries whose relations all have row estimates (03960_*, 04341, 04342, 05216) keep the heuristic.

Related: #120921
Related: #120176

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Join reordering assumes an FK->PK relationship for equi joins without NDV statistics when both sides have row estimates, which produces better join orders for tables without column statistics.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/121075]

Version info

  • Merged into: 26.10.1.1721-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7450158]

Summary: ✅


AI Review

Summary

This reland narrows the FK→PK heuristic to equi joins where both sides have row estimates, restores the pre-heuristic cost path when either side is unknown, and keeps the estimated (NDV) reporting / semi-anti selectivity behavior aligned with the current diagnostics. I re-read the current diff and all prior discussion threads; the earlier issues around invented cardinalities, estimated (NDV) mismatches, and semi/anti match fractions are fixed in the current code, and I did not find any new unresolved correctness or high-impact performance problems in the changed paths or tests.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 7450158.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 92.10% 91.80% -0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 162/165 (98.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 74501585d with master b5446bfff (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

12 translation units recompiled, 29 s compile time in total, 12 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits September 27, 2026 02:29
Relanding the FK->PK heuristic of #120176 as is reproduced the regression it was reverted for: `iceberg_suite_tpch` query 4 times out in the performance comparison again (https://s3.amazonaws.com/clickhouse-test-reports/PRs/121075/f19b8377064891f2ad800238a632f4fd6ab8703f/pr/performance_comparison_arm_release_master_head_6_6/report.html), and `tpcds` query 71 became 22 times slower.

Both come from relations without a row estimate (`ReadFromObjectStorageStep`, a `UNION ALL` subquery) mixed with relations with a known size, see #120921:

- `estimateJoinCardinality` returned the known side when the other side was unknown, which produced 1-row estimates for large intermediates and made them the build side. It returns unknown again, as before the heuristic. This also covers outer joins whose preserved side is the unknown one.
- `estimateJoinedRows` (used for the cost) assumed FK->PK with an unknown side, so joining the only relation with a known size cost its whole row count while joins between unknown relations cost 1, and that relation was pushed to the end. With an unknown side the cost is now the smaller side, which matches the cost before the heuristic.

The FK->PK assumption is kept for joins where both sides have row estimates.

Address review: publish the NDV-based selectivity in `DPJoinEntry::selectivity` again, because `EXPLAIN` reports it as `estimated (NDV)`; `effectiveSelectivity` is removed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… the heuristic

With a side without a row estimate the join cardinality is unknown again and the cost no longer penalises the relation with a known size, so these plans and `ResultRows` return to what `master` produced before #120176. The outputs are identical to the references on `master`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@rschu1ze

Copy link
Copy Markdown
Member

@vdimir @fkastrati FYI^^

@rschu1ze

Copy link
Copy Markdown
Member

Does this PR address the same problem as #122305?

alexey-milovidov and others added 2 commits October 3, 2026 15:51
…gain

The previous commit published `SelectivityEstimate::value` in `DPJoinEntry::selectivity`. That value is 1 when a key column has no NDV statistics, while `master` falls back to the row count of the column's relation (an upper bound of its NDV). Fast test failed in `04011_explain_pretty_join`, `04012_explain_pretty_output` and `04891_explain_analyze_join_estimation`, which show `Selectivity: estimated (NDV) 1` instead of `0.01`:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121075&sha=693c0062a5129c95c5684fae7409981512dd3cad&name_0=PR&name_1=Fast%20test

`getColumnStats` now returns both the real NDV and the upper bound, and `SelectivityEstimate::reported_value` keeps the old NDV-style value for `EXPLAIN`. The cost model still uses only the real NDV and the FK->PK assumption, so join orders are unchanged.

#121075

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @rschu1ze No, these are different problems, and they don't overlap in code. #122305 (merged on 2026-10-02) changes how the NDV of the join key is passed up through a join that has already been estimated: outer joins keep the NDV of the preserved side, and anti joins keep their input NDVs. It only matters when NDV statistics exist. This PR covers the case where a key has no NDV at all. In that case, an equi join where both sides have row estimates is costed as FK->PK (the result keeps the larger side), not as a full cross product. This PR has now been merged with master, which includes #122305.

Also pushed 7dcb6cc. It fixes the Fast test failures (04011, 04012, 04891). EXPLAIN shows the NDV selectivity with the row-count fallback again, as on master (estimated (NDV) 0.01). The cost model still uses only real NDVs.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Oct 3, 2026
alexey-milovidov and others added 2 commits October 5, 2026 07:02
…atch fraction

Without reliable NDV statistics `SelectivityEstimate::value` stays 1, so the
match fraction of a semi/anti join became 1 whenever the probe side was
non-empty (a `LEFT SEMI JOIN` of 1000 rows against 10 rows estimated ~1000
kept rows). Use `reported_value` (1 / row-count upper bound of NDV) in that
case, which restores the previous FK->PK-style estimate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the review (semi/anti match fraction fallback, 0960a93). Previous CI failures: Build (amd_fuzzers) was a relocation overflow seen in ~190 PRs and is green on master now; 01660_join_or_any (parallel replicas) is tracked by #123683; 05237_with_expression_alias_scope_descendant fails across ~190 PRs, unrelated to join ordering. The tpcds #10 slowdown (+18% on ARM) is likely related: Q10 is EXISTS-heavy, so it depends on semi-join estimates; this commit restores the old semi-join estimate, so please re-check it on the new run.

alexey-milovidov and others added 2 commits October 6, 2026 04:41
`estimateJoinedRows` costed an equi join with a side of unknown size as the
smaller side, i.e. 1 row. On `master` such a join costs
`selectivity * lhs.value_or(1) * rhs.value_or(1)`, where the selectivity comes
from the NDV or the row count of the key's own relation. When one side is a
sub-join of unknown size (e.g. `customer` x `orders`) and the key belongs to a
relation with a known size (`orders`, sized from the hash table statistics
cache), that cost is far below 1, and it is what makes the greedy algorithm
build that sub-join first. Without it, TPC-H Q5 and Q9 over Iceberg (whose
relations have no row estimates except those from the cache) got different join
orders and became 47% and 16% slower:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/121075/0960a9375b9f531bc7b9ed8663169858deabb006/pr/performance_comparison_arm_release_master_head_3_6/report.html

Now a join with an unknown side uses `reported_value` (the same selectivity as
on `master`) regardless of `reliable`, so it is costed exactly as on `master`;
the FK->PK assumption applies only when both sizes are known. This also
addresses the review note that the `reliable` path was taken before the check
for a missing row estimate.

Reproduced locally with `Log` tables (no row estimates, as for Iceberg) at
SF10: Q5 0.142 s on `master`, 0.262 s before and 0.153 s after this change;
Q9 0.81 s, 1.05 s and 0.80 s, with the same plans as on `master`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 823f2d4 Oct 7, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the revert-120923-revert-120176-join-order-fk-pk-heuristic branch October 7, 2026 10:08
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Oct 8, 2026
The reproducer of ClickHouse#122301, scaled down 100x and moved to plain MergeTree:
a view LEFT JOINs a fact table without column statistics to four dimension
tables, and a filter on one of them converts that join to INNER. Before
ClickHouse#121075 the join of the fact table with the filtered dimension table was
estimated at the dimension table's size, so the swap put it on the build
side of the three remaining outer joins (3 RIGHT joins). After ClickHouse#121075 they
stay LEFT. The test counts the join types in `EXPLAIN actions = 1`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants