Skip to content

Join reordering: FK->PK heuristic for equi joins without NDV statistics - #120176

Merged
novikd merged 1 commit into
masterfrom
vdimir/join_reorder_no_stats_heuristic
Sep 17, 2026
Merged

novikd merged 1 commit into
masterfrom
vdimir/join_reorder_no_stats_heuristic

Conversation

@vdimir

@vdimir vdimir commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Related: #107637

Extracted from #107637 so that the cost-model change lands first, independently of merging Filter steps 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 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 with value, reliable (backed by real NDV) and has_equi (an equality predicate connects the sides), and estimateJoinCardinality / computeJoinCost distinguish the cases:

  • 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 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 by EXPLAIN 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):

  • Improvement

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

  • Improve join cardinality estimation when column statistics are missing: an equi join without NDV statistics is assumed to be a foreign-key to primary-key join and keeps the larger side, instead of being estimated like a cross product; the greedy join order algorithm prefers equi-connected pairs over pairs linked only by non-equi predicates.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.59 (included in 26.10 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a42ceae]

Summary: ✅


AI Review

Summary

This 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 SEMI/ANTI DPsub path by inflating its plan cost. CI is green, but the claimed Improvement is still not backed by any before/after performance evidence.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/joinOrderCommon.h:70] has_equi is set for every equality predicate, including computed join expressions merged into the graph by query_plan_merge_expression_into_join. For predicates like t1.k % 2 = t2.k % 2 that have no NDV stats and are not FK->PK lookups, the new fallback estimates max(lhs, rhs) rows and can therefore prefer a many-to-many expression join over a real key join. The heuristic needs to be limited to lineage-proven key columns, with a regression covering merged-expression keys.

  • [src/Processors/QueryPlan/Optimizations/enumeratorChecker.h:116] the DPsub conflict-detector path now computes SEMI/ANTI plan cost with the same estimateJoinedRows fallback as a plain inner join. On a missing-stats equi join this turns a LEFT SEMI over [100] and [1000] rows from an old cost of 100 into 1000, even though the preserved side caps the output at 100. That biases the only solver that can reorder SEMI/ANTI joins against pushing them down. The cost estimate should respect strictness here too.

Tests
  • ⚠️ There is still no before/after evidence for the claimed Improvement. All performance-comparison shards on this PR were skipped because it is not labeled pr-performance, so a focused benchmark or at least a targeted EXPLAIN/plan-quality repro is still needed to show the heuristic helps on the intended missing-NDV cases.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Narrow the FK->PK fallback so it does not fire for merged expression keys that are not real lookup keys.
  • Make the DPsub SEMI/ANTI cost path respect join strictness.
  • Add focused evidence that the new heuristic improves plan choice on the intended workloads.

LLVM Coverage Report

Measured on commit a42ceae.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 80.50% 80.50% +0.00%

Changed lines: Changed C/C++ lines covered: 172/175 (98.29%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Sep 15, 2026
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a42ceaece with master e52381d19 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 25a638e44; 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, 28 s compile time in total, 12 of them have a recent master baseline.

Job report

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Comment on lines +107 to +108
if (selectivity.has_equi)
return std::max(lhs_rows, rhs_rows);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does not take into account the fan out during JOIN, but it could be addressed separately.

@novikd
novikd added this pull request to the merge queue Sep 17, 2026
@novikd novikd self-assigned this Sep 17, 2026
Merged via the queue into master with commit 07f2c40 Sep 17, 2026
347 of 348 checks passed
@novikd
novikd deleted the vdimir/join_reorder_no_stats_heuristic branch September 17, 2026 21:10
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Sep 19, 2026
…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
alexey-milovidov pushed a commit to vitlibar/ClickHouse that referenced this pull request Sep 19, 2026
…oin_reorder_no_stats_heuristic"

This reverts commit 07f2c40, reversing
changes made to 2493bb8.
PedroTadim added a commit that referenced this pull request Sep 19, 2026
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]>
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 20, 2026
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)).
@fm4v

fm4v commented Sep 23, 2026

Copy link
Copy Markdown
Member

alexey-milovidov added a commit that referenced this pull request Sep 27, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Sep 27, 2026
… 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]>
raimannma pushed a commit to raimannma/ClickHouse that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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.

4 participants