Skip to content

Add the DPsub join-order enumeration algorithm - #107351

Merged
fkastrati merged 55 commits into
ClickHouse:masterfrom
fkastrati:my-joinopt-wip-branch
Jul 1, 2026
Merged

fkastrati merged 55 commits into
ClickHouse:masterfrom
fkastrati:my-joinopt-wip-branch

Conversation

@fkastrati

@fkastrati fkastrati commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

Motivation

The cost-based join-order optimizer currently offers two enumeration strategies,
selectable via query_plan_optimize_join_order_algorithm: greedy (fast but
often suboptimal) and dpsize (optimal but comparatively expensive). This PR
introduces a third option, dpsub, which produces the same optimal plans as
dpsize while significantly reducing optimization time.

Across chain, star, clique, and cyclic join graphs, dpsub consistently
outperforms dpsize, despite enumerating more CCPs in some cases. The
performance gain comes from a more efficient implementation and reduced
enumeration overhead.

In addition, dpsub supports both inner and non-inner joins, whereas dpsize
can only optimize join orders for inner joins.

The implementation is highly modular and template-based, allowing its
components to serve as building blocks for future work, including dphyp.
The enumerator has been factored into a standalone component (joinEnum.h),
while the DP table and bookkeeping logic have been separated into reusable
structures, with enumChecker.h handling plan acceptance, cost, and
cardinality tracking.

Results

Optimization time for queries with 5 relations across several join-graph
topologies (measured on an M5 MacBook Max). All three algorithms produce the
same final plan, while greedy may select lower-quality execution plans.
dpsub matches the plan quality of dpsize.

Topology Greedy (ms) DPSize (ms) DPSub (ms) DPSize/DPSub
Chain 0.03 0.60 0.03 20×
Star 0.01 0.60 0.04 15×
Clique 0.01 0.42 0.04 10.5×
Cycle 0.02 0.65 0.05 13×

Optimization time for queries with 10 relations:

Topology Greedy (ms) DPSize (ms) DPSub (ms) DPSize/DPSub
Chain 0.10 4.61 0.58 6.7×
Star 0.10 17.82 3.42 5.2×
Clique 0.43 211.36 149.93 1.4×
Cycle 0.10 5.71 1.06 5.4×

dpsub outperforms dpsize across all tested topologies while producing
identical optimal plans. Improvement is most pronounced on sparse graphs
(chain, star, cycle) at 5–20×.

The following benchmarks were run after PR #98798 was merged into master.
That merge also brought improvements to dpsize.
Across all topologies and both relation counts, dpsub yields the
lowest optimization time among the DP algorithms.

Optimization time for queries with 5 relations:

Topology Greedy (ms) DPSize (ms) DPSub (ms) DPHyp (ms) DPHyp/DPSub
Chain 0.03 0.06 0.02 0.05 2.5x
Star 0.02 0.1 0.03 0.15 5x
Clique 0.01 0.04 0.01 0.06 6x
Cycle 0.02 0.08 0.03 0.1 3.3x

Optimization time for queries with 10 relations:

Topology Greedy (ms) DPSize (ms) DPSub (ms) DPHyp (ms) DPHyp/DPSub
Chain 0.11 0.66 0.54 0.35 0.6x
Star 0.12 38.86 8.87 46.15 4.3x
Clique 0.43 90.53 15.45 80.9 5.2x
Cycle 0.1 1.51 0.59 1.13 1.9x

Changelog entry

Added the dpsub join-order enumeration algorithm, providing optimal join
plans with lower optimization overhead than dpsize and support for non-inner
joins.

Version info

  • Merged into: 26.7.1.344 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cfd9646]

Summary: ✅


AI Review

Summary

This PR adds the opt-in dpsub join-order enumeration algorithm and supporting tests/settings. I cannot approve it yet: the current patch still has correctness and resource-control issues in the new DPsub path, including dropped ON predicates and planner resource bounds that do not match the exposed settings.

Missing context / blind spots
  • ⚠️ I could not fetch the machine-readable CI report with .claude/tools/fetch_ci_report.js because the available GitHub token was rejected with HTTP 403. A successful Praktika report fetch would close the CI-status gap.
  • ⚠️ There is no local build directory or clickhouse binary in this checkout, so I did not run the new stateless tests locally.
Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:863] [dismissed by author -- https://github.com/Add the DPsub join-order enumeration algorithm #107351#discussion_r3420217957] DPsub can still drop single-relation ON predicates. This branch still uses edge.fromLeft / edge.fromRight, which only recognize global relation 0 / 1; a predicate like t3.flag = 1 in a flattened 3-way join has source relation 2, so it is not attached at the two-relation step and is skipped later when two_relations is false. That changes query results by omitting a user predicate. Use the source mask itself, e.g. accept non-connecting predicates when sources == 0 || std::popcount(sources) == 1, and add a regression where the filtered relation is not relation 0 or 1 and first joins a multi-relation subtree.
  • [src/Processors/QueryPlan/Optimizations/dpTable.h:51] [dismissed by author -- https://github.com/Add the DPsub join-order enumeration algorithm #107351#discussion_r3458684163] DPsub still allocates the full 2^n table before any search budget can fire. With query_plan_optimize_join_order_limit = 31, this constructs billions of entries and can exhaust memory instead of cleanly falling back. Add a memory/entry-count guard before constructing DPTable, or lower the supported dpsub relation count to a value that is safe for the entry size.

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/joinEnum.h:164] [dismissed by author -- https://github.com/Add the DPsub join-order enumeration algorithm #107351#discussion_r3415283175] DPsub still does not poll checkLimits and its only cap is noCCP() > budget. On disconnected or sparse graphs, noCCP can stay low while the subset loops keep running, so query cancellation/time limits and query_plan_optimize_join_order_max_searched_plans do not bound planning time. Wire the same continueEnumeration/checkLimits mechanism used by the other DP solvers into EnumCcpSub.
  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:1093] [dismissed by author -- https://github.com/Add the DPsub join-order enumeration algorithm #107351#discussion_r3456269389] DPsub ignores the user-visible query_plan_optimize_join_order_max_searched_plans setting and uses a hard-coded 50'000 CCP budget. Setting the limit higher, lower, or to 0 does not affect dpsub, so the documented fallback contract is not true for this algorithm. Pass the configured budget into EnumCcpSub and make 0 mean unlimited consistently.
  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:621] FULL JOIN cardinality is still floored at lhs + rhs, but matching rows are emitted once, so the lower bound is max(lhs, rhs). This overestimates full joins such as two identical 100-row inputs as at least 200 rows and can bias parent join ordering. Use std::max(lhs, rhs) or a proper full-join estimate.
  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:1087] solveDPsub still starts without clearing dp_table, expression_selectivity, or searched_plans, unlike solveGreedy, solveDPsize, and solveDPhyp. If an earlier algorithm in a fallback chain partially populated the optimizer-level caches, computeSelectivityMask can read stale column stats/selectivities while DPsub stores its real state in the local checker. Reset the same optimizer-local state at the start of solveDPsub.
Tests
  • ⚠️ Add a focused dpsub result test for a single-relation ON predicate on a relation id greater than 1, including a shape where the predicate would only be attachable above a multi-relation subtree.
  • ⚠️ Add coverage for query_plan_optimize_join_order_max_searched_plans with dpsub, including a low limit and 0 unlimited.
  • ⚠️ Add a small FULL JOIN cardinality/order regression and a fallback-chain test such as dpsize,dpsub or dphyp,dpsub to prove solveDPsub starts from clean cost-model state.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix the dropped-predicate correctness issue, add a safe DPsub memory/search-budget guard that honors the setting, correct the FULL JOIN estimate, reset DPsub solver-local state, and add the focused regression coverage above.

@fkastrati fkastrati assigned ahmadov and fkastrati and unassigned ahmadov Jun 12, 2026
@fkastrati
fkastrati requested a review from ahmadov June 12, 2026 16:27
@fkastrati
fkastrati force-pushed the my-joinopt-wip-branch branch 3 times, most recently from a8367d1 to fd0b982 Compare June 12, 2026 16:38
@fkastrati
fkastrati force-pushed the my-joinopt-wip-branch branch from fd0b982 to c5145d1 Compare June 12, 2026 16:42
@ahmadov ahmadov self-assigned this Jun 12, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 14, 2026
… Also changed the history values so that the new algorithm gets invoked in the tests
@rschu1ze rschu1ze added the can be tested Allows running workflows for external contributors label Jun 15, 2026
Comment thread src/Core/Settings.cpp Resolved
@fkastrati
fkastrati enabled auto-merge June 24, 2026 17:25
@fkastrati
fkastrati disabled auto-merge June 25, 2026 11:10

@ahmadov ahmadov left a comment

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.

in general, LGTM 👍

I'd consider only fixed 50'000 and memory allocation before checking max_num_ccp a blocker to merge, otherwise it's in a good shape.

Comment thread src/Core/Settings.cpp Resolved

bool isConnected(TUInt S) const { return table[S].count; }
size_t numRelations() const { return num_relations; }
UInt64 noCcp() const { return nr_ccp; }

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.

I guess both noCcp() and nr_ccp should use the same name. Maybe numCcp or numCCP?

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.

I'm using snake_case for variables this way we're coherent with the style guide and the rest of the code in our code base. I will change however noCcp to noCCP.

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.

ah sorry for confusion, I meant numCCP() for the function and num_ccp for the variable. But it's fine with the current state.

UInt64 noCsg() const { return map().size(); }
const Map & map() const { return table; }

void printStatistics() const;

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.

no caller for printStatistics, just remove it?

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.

these are actually quite useful. We need such stats for debugging as well as for comparison over enumeration space explored by different enumeration algorithms. Further, using such stats one can easily measure the efficiency of an algorithm (vs. elapsed time).

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.

What about printing that statistics behind a settings named something like dpsub_print_statistics / print_join_enumeration_statistics (require implementation for all algorithms)? That way we can get the statistics from the running server. Would that make sense? It's up to you

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.50% +0.10%
Functions 92.60% 92.70% +0.10%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 308/332 (92.77%) · Uncovered code

Full report · Diff report

@fkastrati
fkastrati added this pull request to the merge queue Jul 1, 2026
Merged via the queue into ClickHouse:master with commit 1322ce4 Jul 1, 2026
174 checks passed
@fkastrati
fkastrati deleted the my-joinopt-wip-branch branch July 1, 2026 11:13
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…anch

Add the DPsub join-order enumeration algorithm
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 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