Skip to content

Preserve outer-join key NDV estimates - #122305

Merged
cv4g merged 2 commits into
masterfrom
outer-semi-anti-aware-join-key-ndv-min
Oct 2, 2026
Merged

cv4g merged 2 commits into
masterfrom
outer-semi-anti-aware-join-key-ndv-min

Conversation

@cv4g

@cv4g cv4g commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Extracted from #121736.

Previously, equi-join key distinct-value estimates were unconditionally reduced to the minimum estimate from both inputs. This was incorrect for join sides whose rows or key domain are preserved.

This PR introduces a shared helper used by both the join-order optimizer and Cascades statistics derivation. It handles outer, semi, and anti joins consistently while deduplicating the propagation logic.

Changelog category (leave one):

  • Performance Improvement

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

Improves JOIN cardinality estimation by propagating join-key distinct-value estimates according to join semantics. Outer joins retain the preserved-side estimate, anti joins keep their input estimates, and semi joins narrow only the output side, preventing underestimation that could lead to suboptimal query plans.


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

Version info

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

Tighten equi-join key distinct counts only on sides that can lose rows, preserving outer and anti join inputs while filtering the output side of semi joins. Share the propagation helper between join ordering and Cascades.
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12cec9d]

Summary: ✅


AI Review

Summary

This PR factors outer/semi/anti-aware join-key NDV propagation into a shared helper and updates the aggregation-pushdown expectations that change as a result. The remaining gap is that supported null-safe equi-joins still bypass the new propagation entirely, and the PR does not yet include focused runtime evidence for the claimed Performance Improvement.

Findings
  • ⚠️ Majors
  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:91, src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:310] IS NOT DISTINCT FROM is already treated as a join key elsewhere, but both NDV-propagation call sites still gate on JoinConditionOperator::Equals. Outer/semi/anti null-safe joins therefore keep the pre-fix NDV behavior, so the optimizer regression this PR addresses still reproduces on a supported join-key form.
  • Suggested fix: include JoinConditionOperator::NullSafeEquals in both call sites and add a focused regression test for a null-safe outer/semi join.
Tests
  • ⚠️ The PR is labeled Performance Improvement, but the added evidence is plan-shape-only (EXPLAIN reference changes) and the generic cloud benchmark report shows no_change. Please add one focused before/after measurement or a small perf test for the motivating left-join case so the claimed improvement is backed by runtime evidence.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  • Handle NullSafeEquals in both NDV-propagation paths so the fix applies to all supported equi-join keys.
  • Add focused before/after evidence for the claimed performance improvement, or narrow the changelog/PR claim accordingly.

LLVM Coverage Report

Measured on commit 12cec9d.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.50% -0.10%

Changed lines: Changed C/C++ lines covered: 54/54 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

This PR only changes how the join-order and cascades planners estimate distinct join-key counts for outer, semi and anti joins, plus the matching tests. The one flagged query, clickbench Q23 at -40.7% (86 ms to 51 ms), reads a single table and has no joins, so it never runs the changed code. The base measurements were very noisy and the query has been trending on master, so it is downgraded to not_sure. No tpch_adapted_1_official queries were flagged, even though that benchmark is where multi-join planning changes would show up.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 23 not_sure 86 51 -40.7% <0.0001 Q23 reads a single table with no joins, so the changed join key distinct-count estimation never runs for it. The base runs were very noisy and the query is already trending on master, so the -40.7% is not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: c41e1f8c-25aa-42aa-9ce1-c624bb549d89
  • MIRAI run: 3e724510-a197-4b98-aacd-cdcc66b06d94
  • PR check IDs:
    • clickbench_2209508_1790595568
    • clickbench_2209521_1790595568
    • clickbench_2209527_1790595568
    • tpch_adapted_1_official_2209533_1790595568
    • tpch_adapted_1_official_2209545_1790595568
    • tpch_adapted_1_official_2209579_1790595568

@m-selmi m-selmi self-assigned this Sep 28, 2026

@m-selmi m-selmi 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.

Looks good besides the minor fast-test fix!

Preserving the fact key NDV across a `LEFT JOIN` makes the near-unique case local and allows partial aggregation in the three-join case. Update their `EXPLAIN` references and comments.
left_it->second.num_distinct_values = min_ndv;
right_it->second.num_distinct_values = min_ndv;
QueryPlanOptimizations::updateJoinKeyDistinctCounts(
left_it->second,

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.

IS NOT DISTINCT FROM / JoinConditionOperator::NullSafeEquals is already treated as an equi-join key elsewhere (for example joinOrderCommon::computeSelectivity and gtest_join_spill_trigger_plan_setting.cpp both rely on that), but this path still only reaches updateJoinKeyDistinctCounts for Equals. As a result, a LEFT/RIGHT/FULL/SEMI/ANTI join written with a null-safe key keeps the pre-fix NDV propagation in both join ordering and StatisticsDerivation, so the optimizer bug this PR is fixing still reproduces on a supported join-key form. Please route NullSafeEquals through the same update in both call sites.

SELECT '-- 2b. negative: non-deterministic join condition function (`rand`) blocks the pushdown, classic shape';
EXPLAIN SELECT count() FROM t_push_facts AS t1 LEFT JOIN t_push_dims AS t2 ON t1.key = t2.key AND rand() % 2 = 0 GROUP BY t1.key;

-- Preserving the left key's NDV after the `LEFT JOIN` makes a local aggregation cheaper

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 comment is the core performance claim of the PR, but the added evidence only shows that the chosen plan shape changed. Since NDV heuristics can also make a query slower by steering it to a different plan, can we add one focused before/after measurement for this motivating case (even EXPLAIN ANALYZE or a small perf test would be enough)? The generic cloud benchmark report on the PR is no_change, so there is not yet evidence behind the Performance Improvement changelog category.

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 12cec9d7f with master 662762793 (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

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

Job report

@rschu1ze

Copy link
Copy Markdown
Member

Does this address the same problem as #121075?

@cv4g

cv4g commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

Does this address the same problem as #121075?

No, it's a different mechanism. This one here, makes sure that the correct NDV is propagated depending on the join type. The other one is addressing an foreign key related NDV heuristic.

@cv4g
cv4g added this pull request to the merge queue Oct 1, 2026
@cv4g
cv4g removed this pull request from the merge queue due to a manual request Oct 1, 2026
@cv4g
cv4g added this pull request to the merge queue Oct 2, 2026
Merged via the queue into master with commit 1b7e6cd Oct 2, 2026
149 checks passed
@cv4g
cv4g deleted the outer-semi-anti-aware-join-key-ndv-min branch October 2, 2026 15:37
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
eliangidoni pushed a commit to eliangidoni/ClickHouse that referenced this pull request Oct 7, 2026
… counts

Cascades keeps row estimates as Float64 because a cross product of large
inputs can exceed the UInt64 range, and the cost model compares such
values. Distinct-value counts are UInt64, and ten places in
StatisticsDerivation.cpp turned an estimate into one with a plain cast,
which is undefined behavior for values of 2^64 and above. Since ClickHouse#122305
the join-key bound casts each input's row count separately, so one huge
input of an equality join is enough.

The AST fuzzer hit it with TPC-H Q18 from
05024_tpch_join_order_plans_aggregation_pushdown with its ANDs turned
into ORs: customer x orders x lineitem is a 1.35e24-row cross product
under the SF100 hints, and it is the left input of the semi join made by
rewrite_in_to_join (STID 4584-4b08, StatisticsDerivation.cpp:304).

Add toUInt64Saturating to RelationStatistics, next to the statistics
helpers shared with join ordering, and use it at every conversion. It is
identical to the plain cast below 2^64. Clamping the estimate itself
would flatten the cost model, and std::min with Float64(UINT64_MAX) is
2^64, still out of range, hence the >= check.

The test reaches the left and right join keys, an aggregation key,
DISTINCT and INTERSECT. Its INTERSECT query projects columns of both
cross product inputs: with only one input's columns the cross product
returns no rows under the distributed Cascades plan, on master too.

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-performance Pull request with some performance 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