Skip to content

Fix join NDV propagation for distributed aggregation - #114614

Closed
XuJia0210 wants to merge 7 commits into
ClickHouse:masterfrom
XuJia0210:xujia/fix-join-ndv-propagation-public
Closed

XuJia0210 wants to merge 7 commits into
ClickHouse:masterfrom
XuJia0210:xujia/fix-join-ndv-propagation-public

Conversation

@XuJia0210

@XuJia0210 XuJia0210 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Preserve NDV statistics across optimized inner joins so distributed planning can choose partial aggregation for low-cardinality GROUP BY queries instead of shuffling all joined rows.

Description

An optimized JoinStepLogical has two children, so estimateReadRowsCount returned before reading its saved result-column statistics. Move the optimized-join handling before the generic single-child guard so row estimates and column statistics propagate to downstream planning.

The regression test verifies that a low-NDV GROUP BY after an inner join selects partial aggregation. It pins the join-order limit and distributed aggregation mode to isolate the planner behavior from injected settings and exchange execution details.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d98b3ba]

Summary: ✅


AI Review

Summary

This PR moves optimized JoinStepLogical handling ahead of the generic single-child guard in estimateReadRowsCount and remaps stored join-output column statistics through the join DAG, which restores NDV propagation into distributed-aggregation planning and updates the affected plan references. I did not find any remaining correctness or performance findings in the current code; the earlier JOIN USING concern does not apply to the current inner-join path.

Final Verdict

✅ Approve.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 13/14 (92.86%) · Uncovered code

Full report · Diff report

@XuJia0210
XuJia0210 force-pushed the xujia/fix-join-ndv-propagation-public branch from 298cd25 to a2357ec Compare August 13, 2026 09:49
@XuJia0210
XuJia0210 requested a review from rschu1ze August 13, 2026 09:52
@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 13, 2026
@XuJia0210 XuJia0210 added the can be tested Allows running workflows for external contributors label Aug 14, 2026 — with ChatGPT Codex Connector
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes how result-row and column statistics propagate through logical joins in the join-order optimizer, so it affects plans that contain joins. The three flagged ClickBench queries (Q18, Q31, Q34) are single-table aggregations with no joins and cannot exercise the changed path; their +6-11% deltas all fall inside master's current variance band, so the deterministic envelope suppression is correct and these are noise, not regressions. Notably the join-heavy tpch_adapted_1_official benchmark, which is what this change actually targets, produced no flagged queries. No real performance regression is attributable to this PR.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1098 1195 +8.8% <0.0001 aggregation: Q18 is a single-table aggregation with no joins, so this join-order statistics fix cannot reach its plan; the +8.8% sits inside master's variance band and reads as noise.
⚠️ 31 not_sure 299 332 +11.2% <0.0001 aggregation: Q31 is a single-table GROUP BY with no joins; the changed join-order estimation path is never exercised, and the +11.2% falls within master's current variance band.
⚠️ 34 not_sure 1167 1239 +6.2% <0.0001 aggregation: Q34 is a single-table aggregation with no joins, off the changed code path; the +6.2% stays inside master's variance band and is run-to-run noise.

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: d646defa-d949-4f7b-a9b6-691d89727cb1
  • MIRAI run: 30fdc479-4666-43af-b919-71b17185720b
  • PR check IDs:
    • clickbench_62927_1787130169
    • clickbench_62933_1787130169
    • clickbench_62941_1787130169
    • tpch_adapted_1_official_62956_1787130169
    • tpch_adapted_1_official_62968_1787130169
    • tpch_adapted_1_official_62998_1787130169

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d98b3ba09 with master 6c8e5b139 (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
Binary Master PR Δ
programs/clickhouse-stripped 703.88 MiB 700.84 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

9 object files changed (+32.72 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/castOrDefault.cpp.o 1.10 MiB 1.13 MiB +30.61 KiB (+2.71%)

737 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

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

Job report

return aggregation_stats;
}

if (const auto * join_step = typeid_cast<const JoinStepLogical *>(step); join_step && join_step->isOptimized())

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.

The same fix was already attempted #97114 and was reverted in #99957 because of perf regressions https://github.com/ClickHouse/clickhouse-private/issues/52864

A more robust fix is investigated here #101398

@rschu1ze rschu1ze closed this Aug 31, 2026
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
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 pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants