Skip to content

Split JoinOrderOptimizer - #116684

Merged
rschu1ze merged 12 commits into
masterfrom
join-order-optimizer-refactoring
Sep 1, 2026
Merged

rschu1ze merged 12 commits into
masterfrom
join-order-optimizer-refactoring

Conversation

@cv4g

@cv4g cv4g commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

CI-only change set at the moment.

Review is best performed commit by commit. The changes are mostly byte-identical code moves. Some former member functions were converted to free functions. Their call sites are adapted.

Summary

Previously, all join-order algorithms and their mutable state were contained in joinOrder.cpp and the private JoinOrderOptimizer class:

  • joinOrder.cpp: 1,810 lines
  • JoinOrderOptimizer: 29 declared member functions and 15 instance data members
    (Greedy relies on 7 member functions / 4 data members; DPsize: 9 / 8; DPhyp: 17 / 12; DPsub: 10 / 5)

After this change:

  • joinOrder.cpp: 377 lines
  • JoinOrderOptimizer: remains as entry point and coordinator, with 2 member functions and 6 data members
  • Each algorithm has a private class and translation unit:
Scope Function kind Functions Data members
JoinOrderOptimizer coordinator Member 2 6
Greedy optimizer Member 2 4
DPsize optimizer Member 3 8
DPhyp optimizer Member 11 12
DPsub optimizer Member 8 5
Common cost/statistics helpers Free 5 —
Dynamic-BitSet helpers Free 3 —
DPsize/DPhyp candidate helpers Free 2 —

Changes

  • Extracted common cost, cardinality, statistics, and selectivity helpers.
  • Extracted dynamic-BitSet graph helpers and shared DP candidate evaluation.
  • Moved Greedy, DPsize, DPhyp, and DPsub into independent implementations.
  • Retained DPsub's specialized native-mask path and dense table integration.
  • Reduced JoinOrderOptimizer to ordered fallback dispatch and overall reporting.
  • Preserved the public interface, algorithm order, fallback behavior, search budgets, enumeration order, tie-breaking, and algorithm capability restrictions.
  • Isolated each attempt's memo and selectivity state. DPsub no longer observes partial state from a failed DPsize or
    DPhyp attempt.
  • Added regression coverage comparing standalone DPsub with dphyp,dpsub and dpsize,dpsub fallback chains.
  • Applied the existing AMD64 Debug -O2 workaround to the extracted translation units and reused a cached optimizer logger.

No existing test reference files are changed.
No functional changes (the DPsub partial state observation aside).

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not for changelog


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

Version info

  • Merged into: 26.9.1.476 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d287ac]

Summary: ✅


AI Review

Summary

This PR splits JoinOrderOptimizer into per-algorithm translation units, carries the existing debug-amd64 -O2 workaround over to the extracted files, and fixes the DPsub fallback-state leak by clearing its memo and selectivity caches before a fallback run. I did not find a correctness or compatibility regression in the current code: the extracted algorithm bodies stay materially aligned with the pre-split implementation, and the new stateless test covers the one intentional behavioral change.

Missing context / blind spots
  • ⚠️ amd_debug, sanitizer, and the remaining build jobs were still pending on 2026-08-27 while I reviewed. A clean run there would close the last execution-level gap around the file split and the widened -O2 workaround.
Final Verdict

✅ No review findings in the current patch.

LLVM Coverage Report

Measured on commit 5d287ac.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 643/699 (91.99%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5d287ac5c with master 24e639f8d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.28 MiB -3.05 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 ⚠️

5 object files changed (+437.34 KiB total), 6 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrder.cpp.o 656.93 KiB 208.27 KiB -448.66 KiB (-68.30%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderDPHyp.cpp.o new 239.05 KiB +239.05 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderGreedy.cpp.o new 196.95 KiB +196.95 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderDPSub.cpp.o new 185.60 KiB +185.60 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderDPSize.cpp.o new 114.39 KiB +114.39 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderDP.cpp.o new 92.82 KiB +92.82 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderBitSet.cpp.o new 57.17 KiB +57.17 KiB

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

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

Job report

@cv4g

cv4g commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

@groeneai

Copy link
Copy Markdown
Collaborator

Not caused by your PR. It is a known master defect that I already have a fix open for.

AST fuzzer (amd_debug, targeted, old_compatibility) aborted on Logical error: 'key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0' (STID 2508-5166) at src/Storages/MergeTree/KeyCondition.cpp:5033. Stack: executeQuery -> InterpreterUpdateQuery::execute -> StorageMergeTree::updateLightweight -> MutationsInterpreter::execute -> ReadFromMergeTree::selectRangesToRead -> KeyCondition::checkInRange. That is primary key index analysis, and there is no join-ordering frame anywhere in the stack.

The aborting query is UPDATE t_lwu_key_prefix__fuzz_0 SET v = 'baz' WHERE a >= 900, a fuzzed clone of 04509_lwu_sorting_key_common_prefix.sql. The targeted fuzzer seeded 28 tests for this job: 1 changed test from your diff (05045_join_order_dpsub_fallback_state) and 27 coverage-relevant ones, and 04509 is in the second group. So the seed came from the coverage step, not from your change.

Root cause: ALTER TABLE ... MODIFY ORDER BY is accepted when it changes a sorting key column's sort direction, while the parts already on disk keep the old physical order, so key analysis compares the new metadata against boundary values read from the old index. #116473 refuses that ALTER, which closes this consumer and the merge and mutation ones too.

On the re-run: the plain AST fuzzer (amd_debug, targeted) passed on the same commit, and this signature has only 2 hits in the last 30 days (the other on an unrelated PR of mine on 2026-08-25), both in the old_compatibility variant. Whether the fuzzer reaches the shape again is luck, so the re-run may still come back red. Either way nothing needs changing on your side.

@Manerone Manerone self-assigned this Sep 1, 2026

@Manerone Manerone 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.

The split looks good to me, I just left one nitpick, but feel free to ignore it.

const BitSet & left,
const BitSet & right);

double computeSelectivity(

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.

nitpick: we have computeSelectivity is other files as well. Since we are making the effort of cleaning JoinOrder.cpp doesn't it also make sense to scope the files (with namespaces) as well? This way we can get: JoinOrderBitSet::computeSelectivity and JoinOrderCommon::computeSelectivity

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thank you! That's a good point. Let's do a follow up for this. I don't have a good overview how far sub namespacing is developed but in any case the name duplication is indeed not good.

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.

Sorry, I approved before running Claude, but it also complained that we end up exposing DB::connects. Which is a bit too generic to export in the DB namespace.

@rschu1ze
rschu1ze added this pull request to the merge queue Sep 1, 2026
Comment on lines +44 to +47
/// Discard any partial state left by an earlier algorithm in the fallback chain
/// (e.g. `dphyp,greedy`) so cost-model lookups via `getColumnStats` only see
/// entries built by this run. `expression_selectivity` is cleared along with
/// `dp_table` because multi-relation predicates resolve NDV through it.

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

Comment on lines +62 to +64
/// Populate DP table for components of size=1.
/// Also reset the per-edge selectivity cache so an earlier algorithm in the
/// fallback chain cannot leak cached `1.0` defaults from a partial `dp_table`.

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.

Outdated comment

Comment on lines +521 to +523
/// Initialize dp_table with a leaf entry for each base relation.
/// Also reset the per-edge selectivity cache so this run is independent of any
/// earlier algorithm in the fallback chain.

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.

Outdated

Comment on lines +350 to +352
/// DPsub uses the generic memo only for composite-expression statistics. Clear any
/// partial state left by an earlier algorithm in the fallback chain so this attempt
/// has the same cost model as a standalone DPsub run.

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.

Outdated

Merged via the queue into master with commit f8fafdc Sep 1, 2026
179 checks passed
@rschu1ze
rschu1ze deleted the join-order-optimizer-refactoring branch September 1, 2026 09:38
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

5 participants