Skip to content

Join reordering: without NDV, assume the smallest table joined on a key holds the unique key - #128102

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/join-order-equivalence-class-ndv-bound
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/join-order-equivalence-class-ndv-bound

Conversation

@groeneai

@groeneai groeneai commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

When join keys have no NDV statistics, the join order optimizer assumes that the smallest of all tables joined on one key holds the unique key, so a join of two larger tables on that key is estimated as many-to-many instead of as a key lookup. Repeat runs of TPC-H Q5 on tables without column statistics no longer time out. Controlled by the new setting query_plan_join_order_equivalence_class_ndv_bound (enabled by default).

Description

Closes: #128094

Without NDV statistics, estimateJoinedRows costs every equi join with both sizes known as FK->PK, max(lhs, rhs), one pair at a time (#120176). In TPC-H Q5, c_nationkey = s_nationkey AND s_nationkey = n_nationkey puts customer and supplier in one key class with the 25-row nation, so customer x supplier on that key is costed 1.5M rows instead of ~6e9. The first run plans well because the filtered inputs have no size; once the hash table statistics of that run give every input a size, the optimizer picks this join and every later run times out.

This PR applies the assumption to the whole key class: its smallest relation (also on neither side) bounds its distinct values, so for exactly one connecting key the estimate is max(lhs, rhs, lhs * rhs / class_min). Composite keys, a side without a size and reliable NDV keep today's rules. Both selectivity paths (greedy/DPsize/DPhyp and DPsub) are changed. compatibility <= '26.10' or the setting = 0 restores the old plans.

Validation: 05331_join_order_one_side_unknown_rows gets greedy and dpsub arms with all sizes known (old plan on master with all four algorithms, new with the patch), the same arms with an extra <=> key (a composite key, old plan kept) and a setting-off control. Synthetic TPC-H SF10 without statistics (debug build, 4 threads): Q5 repeat runs 9/9 over max_execution_time = 60 -> about 1 s, Q5 without filters 3/3 over the limit -> about 3 s, first runs unchanged (same EXPLAIN), same results. The issue author measured TPC-DS without NDV: 151.0 -> 150.6 s total, q65 +3.6% (its GROUP BY key is not known to be unique). This PR's Performance Comparison will not show it: tpch.xml materializes column statistics, and the Iceberg suites run without use_iceberg_manifest_statistics (Q5 about 0.8 s on master).

🤖 Generated with Claude Code


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

groeneai and others added 3 commits October 29, 2026 01:26
… class

Without NDV statistics, `estimateJoinedRows` assumes FK->PK for every
equi join pair separately and keeps `max(lhs, rhs)`. In TPC-H Q5,
`c_nationkey = s_nationkey AND s_nationkey = n_nationkey` puts `customer`
(1.5M rows) and `supplier` (100K rows) in one key class with the 25-row
`nation`, so joining `customer` with `supplier` on that key is costed as
1.5M rows while it produces ~6e9. Once the hash table statistics of a
first run give every input a size, the optimizer picks that join and
every repeat run of Q5 times out.

Apply the FK->PK assumption consistently within the class: its smallest
relation (over all members, also those on neither side) holds the unique
key, so the class has at most that many distinct values. When the two
sides are connected by exactly one join key that is such a class, the
estimate is `max(lhs, rhs, lhs * rhs / class_min)`. Composite keys, a
side without a row estimate and reliable NDV keep today's rules. An equi
condition counts as another join key only when it connects the two sides
and its operands are not in one class.

DPsub keeps its per-candidate work on native masks: the smallest class
member is precomputed once per solve and the side test of the extra-key
count runs on `toMask` of the edge sources.

Gated by the new setting `query_plan_join_order_equivalence_class_ndv_bound`
(default true, `compatibility <= 26.10` restores the old estimate).

Closes ClickHouse#128094

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…timate

`ON ... AND c_nationkey = s_nationkey AND (c_custkey <=> s_suppkey)` connects
`customer` and `supplier` by two keys, one of which (`NullSafeEquals`) is in no
key class, so the equivalence-class NDV bound must not apply and the join keeps
the `max(lhs, rhs)` estimate. Arms under greedy and dpsub. With the guard in
`countUnclassifiedEquiKeys` disabled both arms switch to the all-hints plan
(`customer` joined with `orders` first), so they exercise the guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the setting-pointer and loop-scope comments, shorten the applyEquivalenceClassBound and countUnclassifiedEquiKeys contracts to one line each.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 runs, 2 findings, the re-review of the final head found none) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test never reaches the composite-key guard (countUnclassifiedEquiKeys) AGREE, fixed INNER JOIN ... ON ... AND (c_custkey <=> s_suppkey) arms for greedy and dpsub keep the old plan; with the guard disabled only these two arms change
2 ⚠️ Plan shape proven, end-to-end speed-up not DISAGREE SF10 synthetic A/B, fresh server per run, 3 reps: setting off 9/9 repeat runs over 60 s, on 0.99-1.24 s; same result hash with the reorder limit 0
3 💡 getColumnStats called twice for a side member (BitSet path) DISAGREE hoisting it would compute it with the setting off
4 💡 BitSet connects lambda duplicates connects() DISAGREE joinOrderDP.h includes joinOrderBitSet.h
5 💡 Over-estimate when the smallest class member is a filtered or FK-side table DISAGREE stated in the setting text; TPC-DS 99 without NDV 151.0 -> 150.6 s

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261029-021700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the new arms of 05331_join_order_one_side_unknown_rows (stat hints with row counts and no NDV, pinned plan settings) give the bad Q5 order on master every time.
b Root cause explained? Yes: without NDV, estimateJoinedRows assumes FK->PK per pair, so customer x supplier on the nation key (class with the 25-row nation) is costed 1.5M rows instead of ~6e9.
c Fix matches root cause? Yes: the FK->PK assumption is applied to the whole key class; the smallest member bounds its NDV. No guard, no tag.
d Test intent preserved / new tests added? Yes: 05331 extended with additions only (greedy, dpsub, a composite key with a <=> part, setting-off control); the existing arm and its reference are unchanged.
e Both directions demonstrated? Yes: master and the setting = 0 give the old plan (byte-identical), the patch the new one; synthetic SF10 Q5 repeat runs 9/9 timeouts -> about 1 s, same results.
f Fix is general across code paths? Yes: both selectivity paths (greedy/DPsize/DPhyp and DPsub) are changed and all four algorithms were checked; outer and semi/anti joins cannot form a class across the step.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: Nullable, LowCardinality and LowCardinality(Nullable) keys behave the same; composite keys, NullSafeEquals and expression keys keep the old rule (a c_custkey <=> s_suppkey second key is tested; it changes the plan when the guard is disabled).
h Backward compatible? (maintainer-approved exception only) Yes: new setting with a 26.11 history entry; compatibility = '26.10' turns it off.
i Invariants and contracts preserved? Yes: an estimate is never lowered; the unknown-size and reliable-NDV branches are untouched; DPsub keeps its per-candidate work on native masks.

Session id: cron:clickhouse-impl-slot-4:20261029-020900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @vdimir, could you review this and add the can be tested label so CI runs? Without NDV statistics the join order cost model now bounds a single-key join by the smallest relation of the key's equivalence class, so customer x supplier on the nation key in TPC-H Q5 is costed as many-to-many instead of as a key lookup and repeat runs no longer time out.

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49a8c73]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb

AI Review

Summary

The PR improves join ordering without NDV statistics by estimating single-key joins against the smallest member of the key's equivalence class. Review of head 49a8c731a4e34d4e2a4ab607a42cf6968f1b94dc found no actionable issues.

Missing context / blind spots
  • ⚠️ The current head's release performance comparison is still pending. The PR and linked issue provide before/after measurements, and the updated regression test passes in the current head's Fast test job, but the latest cache optimization has only author-reported local debug measurements. A completed current-head performance comparison would close this validation gap. No local build or query execution was performed.
Final Verdict

Status: ✅ Approve. No required code changes identified.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 49a8c731a with master 2824be836 (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.

Object file sizes

55 object files changed (+48.55 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrder.cpp.o 248.21 KiB 278.85 KiB +30.64 KiB (+12.34%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

`tests/performance/one_thousand_joins.xml` got 55-62% slower with the
class bound on (CI, amd and arm). Every pair the join order search
evaluated rescanned its applicable edges with `asBinaryPredicate` (a
function name copy plus operator name comparisons), `resolveAliases`
and two class lookups to count the keys outside a class, and the
greedy/DPsize/DPhyp path looked up the row count of every class member,
including members on neither side.

Both depend only on the graph, so `QueryGraph::buildEquivalenceClassBounds`
now computes the smallest size of each class and the set of equi edges
outside a class once, before the search. A pair evaluation does one hash
lookup per class and, only when such an edge exists, one per applicable
edge. Plans are unchanged.

Debug build, the perf test query in `clickhouse local`, setting 0 -> 1:
before 2.9 -> 8.0 s (dpsub), 10.3 -> 16.0 s (dphyp), 9.0 -> 14.9 s
(dpsize); after 2.8 -> 2.8, 8.6 -> 8.5, 9.2 -> 9.4 s.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 49a8c73

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: 'Inconsistent AST formatting' (STID: 1941-1bfa) logical error in the AST formatter, not from this PR (it changes only join-order costing): the fuzzed EXPLAIN WHATIF query has a query-parameter table alias before a LOCAL join (LATERAL {fuzz_param_0:Identifier} LOCAL ANTI RIGHT JOIN), the alias is not written back, so the re-parse reads LOCAL as the left table's alias; the same failure hit at least 4 other PRs since 2026-10-23 #120222 (mine, open)
PR praktika rollup of the row above #120222 (the owner of the row above)

The one_thousand_joins slowdown from the previous head is gone on this head (all 12 Performance Comparison shards pass).

Session id: cron:our-pr-ci-monitor:20261029-203004

zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Nov 5, 2026
Base-table NDV can exceed the row count of a multi-relation join input, so `1 / max(NDV)` underestimates the output of the join above it and the optimizer picks a worse order. Cap each join key NDV and NDV upper bound by the estimated rows of its input subtree when that side contains more than one relation.

`SelectivityCache` stores context-independent `JoinKeyStats` instead of a finished `SelectivityEstimate`: the same edge can join different subtrees in another candidate plan, so the row cap is applied after the cache lookup. Both direct predicates and transitive equivalence classes are covered in `dpsub`, `dphyp`, `dpsize`, and `greedy`.

Tests: `05493_join_order_subtree_ndv` checks corrected estimates, cache contexts, and bushy plans. `05494_join_order_subtree_ndv_stable` uses independent tables per algorithm to verify cold and warm `EXPLAIN` plans are identical with hash table statistics enabled.

Historical benchmark (7 runs, discard the first, median of the remaining 6; result hashes identical): TPC-DS Q72 0.1725s -> 0.0835s. TPC-H Q02 unchanged at 0.034s. These figures come from the original benchmark logs and were not rerun for this commit.

Related: ClickHouse#128102

Related: ClickHouse#114614

Related: ClickHouse#101398
@rschu1ze

rschu1ze commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Without statistics, all bets are off ("garbage in - garbage out"). In Berlin, the Join team agreed to ignore this case.

@rschu1ze rschu1ze closed this Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-performance Pull request with some performance improvements v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Join reordering costs a many-to-many join as a key lookup when NDV statistics are missing: TPC-H Q5 times out on repeat runs

4 participants