Skip to content

Cap join key NDV by multi-relation subtree rows - #129663

Open
zoomxi wants to merge 10 commits into
ClickHouse:masterfrom
zoomxi:cardinality
Open

zoomxi wants to merge 10 commits into
ClickHouse:masterfrom
zoomxi:cardinality

Conversation

@zoomxi

@zoomxi zoomxi commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Description

Join reordering estimates an equi join using 1 / max(NDV). When a join key originates from a base table inside an already joined subtree, its base-table NDV can exceed the estimated row count of that subtree. This underestimates the output cardinality of the join above it and can lead to a worse join order.

Cap both the NDV and its upper bound by the estimated row count of the input subtree when that side contains more than one relation. Single-relation inputs retain their existing estimates.

Example

-- 10,000 rows, NDV(k) = 100
CREATE TABLE f(k UInt64) ENGINE = MergeTree ORDER BY k;
-- 1,000 rows, NDV(k) = 1,000, NDV(w) = 100
CREATE TABLE d2(k UInt64, w UInt64) ENGINE = MergeTree ORDER BY k;
-- 10 rows, NDV(w) = 10
CREATE TABLE d1(w UInt64) ENGINE = MergeTree ORDER BY w;

EXPLAIN PLAN indexes = 0
SELECT count()
FROM f
INNER JOIN d2 ON f.k = d2.k
INNER JOIN d1 ON d2.w = d1.w

Before this change is:

f[10000] ⋈ (d2[1000] ⋈ d1[10])
Join conditions: k = k
Selectivity: estimated (NDV) 0.001 · actual (cartesian) 0.01
Output rows: estimated 1.00 thousand · actual 10.00 thousand · q-error 10.00

After this change:

f[10000] ⋈ (d2[1000] ⋈ d1[10])
Join conditions: k = k
Selectivity: estimated (NDV) 0.01 · actual (cartesian) 0.01
Output rows: estimated 10.00 thousand · actual 10.00 thousand · q-error 1.00

Previously, the outer join used selectivity 1 / max(100, 1000) = 0.001, underestimating its output as 1,000 rows.
Capping d2.k by the 100-row input subtree changes the selectivity to 1 / max(100, 100) = 0.01 and the estimated output to 10,000 rows, matching the actual cardinality.

Changelog category (leave one):

  • Improvement

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

Improve cardinality estimation for joins above multi-relation subtrees by capping join-key NDV by the estimated input row count.


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

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
@clickhouse-gh clickhouse-gh Bot added external Author is not a member of the ClickHouse organization comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 6, 2026
@zoomxi

zoomxi commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@cv4g PTAL,thanks.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bdb063c]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
01710_projection_with_mixed_pipeline NOT_FAILED cidb
05033_lazy_materialization_column_function_structure_equals NOT_FAILED cidb
05034_lazy_materialization_column_function_set_capture NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb

AI Review

Summary

Reviewed #129663 at bdb063ca970662f5537b570de0ae6b4194eadd87. The change improves join cardinality estimation by applying subtree row caps to join-key NDVs after cache lookup, with a guard against reversing key containment. Both previous findings are addressed, and no new actionable findings remain. Fast test passed both new SQL regressions and the existing TPC-H join-order plan test at this commit.

Missing context / blind spots
  • ⚠️ Full stateless, unit, and sanitizer CI is pending, including execution of the new EnumeratorCheckerWithCosts regression. No local build or tests were run; completed CI results would close this gap.
  • ⚠️ ARM performance comparisons are pending and AMD comparisons are skipped. Current-head runtime effects remain unverified; completed performance comparisons would provide that evidence.
Final Verdict

Status: ✅ Approve. No outstanding review findings; normal CI checks still need to complete.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 15, 2026
…o cardinality-squashed

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/joinOrderCommon.h
#	src/Processors/QueryPlan/Optimizations/joinOrderDPSub.cpp
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@clickhouse-gh clickhouse-gh Bot added comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 16, 2026
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bdb063ca9 with master 92fdcb78e (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

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

Job report

`1 / max(NDV)` assumes that the keys of the side with fewer distinct values
are contained in the other side. Capping a multi-relation input below the
other side's NDV reverses that assumption: a filtered sample of a large key
domain, such as `customer` joined with a filtered `nation`, was assumed to
match `orders.o_custkey` completely. In TPC-H Q7 this raised the estimate of
`orders ⋈ (customer ⋈ n2)` from 1.2 million (actual 1.2 million) to 1.8
million, and the optimizer picked `orders ⋈ (lineitem ⋈ (supplier ⋈ n1))`
first. That is the `tpch-join_algorithm-partial_merge` ClickHouse#5 regression.

Cap a side only while its input still has at least as many rows as the other
side has distinct keys. Plans of all TPC-H queries at SF10 are now the same as
on `master`, so the `03836_tpch_join_order_plans` reference returns to the
`master` version, and the correlated cases in `05493_join_order_subtree_ndv`
keep their capped estimates. Add a case where the subtree is a sample of the
key domain.

Also use `UnorderedMapWithMemoryTracking` for `SelectivityCache` again, as
`master` requires for `src/Processors/QueryPlan`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=129663&sha=ac91fe8f1912ba540f0cec2155ad89f0c7411cc2&name_0=PR
PR: ClickHouse#129663
@clickhouse-gh
clickhouse-gh Bot dismissed stale reviews from themself November 16, 2026 13:40

AI review of a later commit does not approve the PR, see the AI Review comment.

When the opposite key lacks NDV statistics but has a known row-count upper bound, apply the same containment guard to both the NDV used for costing and the reported upper bound. Add direct and transitive partial-statistics regressions.

ClickHouse#129663
…o cardinality-squashed

Keep per-candidate selectivity in `EnumeratorCheckerWithCosts::acceptMergeJoins` and pass `key_classes` through to `mergeJoinCost`. Adapt the enumerator checker test to that signature.

This branch has not been deployed

No deployments
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... external Author is not a member of the ClickHouse organization pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants