Repository navigation
Join reordering: FK->PK heuristic for equi joins without NDV statistics - #120176
Conversation
Extracted from #107637 so that the cost-model change lands independently of merging filters into the join. Before, a join key without column statistics used the relation row count as its NDV, so `a[1000] JOIN b[100]` was estimated as `1000 * 100 / 1000 = 100` rows, and an equi join looked the same as a cross product once statistics were missing. `computeSelectivity` now returns a `SelectivityEstimate` carrying `value`, `reliable` (backed by real NDV) and `has_equi` (an equality predicate connects the sides). `estimateJoinCardinality` and `computeJoinCost` use it as follows: - reliable NDV: `selectivity * lhs * rhs` as before; - equi join without NDV: assume FK->PK, the result keeps the larger side; - no equi condition (cross or range-only join): the full product; - one side unknown: the known side for an equi join, unknown otherwise. The greedy solver ranks equi-connected pairs above pairs linked only by non-equi predicates, so a bare cross product that happens to be enumerated first no longer shadows valid equi-joined plans, while pairs linked only by range predicates stay joinable. `DPJoinEntry::selectivity`, shown by `EXPLAIN ANALYZE`, is the effective selectivity implied by the heuristic (`effectiveSelectivity`), so it stays comparable with the actual cartesian selectivity when no NDV is known. Test references are updated for the new estimates; the `03960_join_order_dphyp_*` tests pin `materialize_statistics_on_insert = 1` because the plans they assert on now depend on the statistics being present. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [a42ceae] Summary: ✅
AI ReviewSummaryThis PR changes the join-order cost model so equi joins without NDV statistics are treated as FK->PK lookups, and the greedy solver now prefers equi-connected pairs over non-equi-only pairs. I am requesting changes because the new heuristic is applied more broadly than the PR contract supports: it now covers merged expression keys that are not key lookups, and it regresses the opt-in Findings
Tests
Final VerdictStatus: Minimum required actions:
LLVM Coverage ReportMeasured on commit a42ceae.
Changed lines: Changed C/C++ lines covered: 172/175 (98.29%) · Uncovered code |
| UInt64 lhs_ndv = getColumnStats(query_graph, dp_table, lhs.getSourceRelations(), lhs.getColumnName()); | ||
| UInt64 rhs_ndv = getColumnStats(query_graph, dp_table, rhs.getSourceRelations(), rhs.getColumnName()); | ||
| UInt64 max_ndv = std::max(lhs_ndv, rhs_ndv); | ||
| estimate.has_equi = true; |
There was a problem hiding this comment.
This flips the new heuristic on for every = / <=> predicate, but the join graph is not limited to raw key columns. With query_plan_merge_expression_into_join = 1 we already flatten computed join keys into this path, and multi-argument expressions like t1.k % 2 = t2.k % 2 do not preserve the FK->PK shape at all. Once both sides miss NDV stats, estimateJoinedRows will now cost that join as max(lhs, rhs) even though it can still be many-to-many, so greedy/DP can prefer an expression join ahead of a true keyed join. Please gate has_equi here on lineage-proven key columns (or at least simple single-relation input columns), and add a regression for merged-expression join keys.
| @@ -115,7 +116,7 @@ EnumeratorCheckerWithCosts<TDPTable, TOptimizer>::accept(const UInt result_subse | |||
| auto plan_cost = computeJoinCost(lhs_subset, rhs_subset, selectivity); | |||
There was a problem hiding this comment.
This now over-costs reordered SEMI/ANTI joins in the conflict-detector path because we already know strictness above, but computeJoinCost still uses the plain inner-join fallback. For a LEFT SEMI with [100] preserved rows joined to [1000] rows and no NDV stats, the old fallback cost was 100 * 1000 / 1000 = 100; after this patch it becomes max(100, 1000) = 1000, even though the join can never emit more than the preserved side. That pushes exactly the selective semi/anti joins we want to reorder later in DPsub. Please thread strictness into the cost estimate (or clamp SEMI/ANTI to their preserved side here as well).
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units12 translation units recompiled, 28 s compile time in total, 12 of them have a recent master baseline. |
| if (selectivity.has_equi) | ||
| return std::max(lhs_rows, rhs_rows); |
There was a problem hiding this comment.
It does not take into account the fan out during JOIN, but it could be addressed separately.
…rdict The `Check Results` status of a `master_head` performance shard failed only when more than 10 queries were "slower". A single large regression therefore passed: ClickHouse#120176 was merged with `tpcds` query 71 going from 0.24 s to 5.67 s (+2225%) on arm, reported as `1 slower` and green, while the performance dashboard classified it as `confirmed_regression`: https://performance.ci.clickhouse.com/runs/pr-120176-a42ceaeced57aba347467f9940f33abe4fb50388 The dashboard computes a run from the tables this job uploads in the REPORT stage and judges every changed query with a confidence tier built from the raw per-run samples of both sides, the quantile shift and the recent master history of the same query. In `master_head` mode that verdict now decides the status: after the uploads, the job waits until the dashboard serves this shard's data (the `/tests/<test>` detail lists this arch), fetches `/runs/<run>/confidence` for `client_time`, keeps the slowdown rows of this shard and arch, and fails the check when any of them is `confirmed_regression`. The confirmed rows are added to `Check Results` with a link to the dashboard's query page. If the dashboard does not answer within ten minutes the check fails with the reason instead of passing an unjudged run. The `release_base` mode keeps its delta gate on slower counts, because that comparison is cumulative since the release branch point and is not what the dashboard's PR runs describe. Related: ClickHouse#120921
Conflict in `03835_join_transitive_predicates_dedup.sql`: master dropped `SET materialize_statistics_on_insert = 1` in 7e17a19, the revert of #120176, while this branch added a `query_plan_optimize_join_order_max_searched_plans` pin just above it. Kept the pin, honoured the deletion. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md. Changelog-revert: 120268 109097 Revert "Add zero-argument year() returning the current year" Changelog-revert: 120877 120801 Revert "Revert "CI: give revert pull requests a green light at once"" Changelog-revert: 120923 120176 Revert "Join reordering: FK->PK heuristic for equi joins without NDV statistics" Changelog-revert: 120931 120930 Revert "Revert "Do not allocate from peer-declared sizes when reading settings from the Native protocol"" Changelog-deleted-entry: 120176 [Performance Improvement] [section] * Improve join order selection when column statistics are missing: an equi join without NDV statistics is now treated more like a foreign-key to primary-key join instead of a cross product, and the greedy join-order algorithm prefers equi-connected pairs over pairs linked only by non-equi predicates. [#120176](#120176) ([Vladimir Cherkasov](https://github.com/vdimir)).
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]>
…hboard does not answer In `master_head` mode `main` turned every `PerfDashboardError` into a failure, and nothing told an outage of CIDB or of the dashboard from a defect of the job. On ClickHouse#116101 at 3b7362d, 5 of 12 shards failed during the 2026-10-13 CIDB outage although every shard report found 0 slower queries. - `CIDBCluster.last_unavailable`: the last failed call met a transport error, an answer without `X-ClickHouse-Exception-Code` (not from the server), or the server's own-load code 202 (also 241 for the `SELECT 1` probe; an INSERT can exceed a memory limit by itself). `last_rejected` and the retry decisions are unchanged. - `insert_into_cidb` tags a budget-spent reason with that, and an upload that never started; the gate counts the missing inputs as unavailable only when a classified outage spent the budget. - `dashboard_api_get` raises `PerfDashboardUnavailable` for transport errors, a gateway 502/503/504, a 404 with the backend's `code = NotFound`, and the measured outage messages `connect: connection refused` and `context canceled`. At the deadline the gate raises the class of the last reason, so a persistent wrong answer still fails. - On `PerfDashboardUnavailable` the shard is judged by its own summary: any slower query fails it (the gate exists because "more than 10 slower" passed a single +2225% query in ClickHouse#120176). An invalid summary still fails. - `/confidence` is retried until the deadline (a single HTTP 500 failed a shard on ClickHouse#124320). - `insert_historical_data` no longer prints its TSV twice: on amd 1/6 that took 15 of the last 17 s of the budget. Requested in ClickHouse#116101 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #107637
Extracted from #107637 so that the cost-model change lands first, independently of merging
Filtersteps into the join.When a join key has no column statistics, the join order optimizer used the relation row count as its NDV, so
a[1000] JOIN b[100]was estimated as1000 * 100 / 1000 = 100rows, and an equi join looked the same as a cross product once statistics were missing.computeSelectivitynow returns aSelectivityEstimatewithvalue,reliable(backed by real NDV) andhas_equi(an equality predicate connects the sides), andestimateJoinCardinality/computeJoinCostdistinguish the cases:selectivity * lhs * rhsas before;The greedy solver ranks equi-connected pairs above pairs linked only by non-equi predicates, so a bare cross product enumerated first no longer shadows valid equi-joined plans, while pairs linked only by range predicates stay joinable (new test
05216_join_order_greedy_non_equi_over_cross).DPJoinEntry::selectivity, shown byEXPLAIN ANALYZE, is the effective selectivity implied by the heuristic, so it stays comparable with the actual cartesian selectivity when no NDV is known.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/120176]
Version info
26.10.1.59(included in26.10and later)