Skip to content

Add auto mode to query_plan_optimize_join_order_algorithm - #99884

Closed
cv4g wants to merge 10 commits into
masterfrom
join-order-algorithm-auto
Closed

cv4g wants to merge 10 commits into
masterfrom
join-order-algorithm-auto

Conversation

@cv4g

@cv4g cv4g commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

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

Users can now configure ClickHouse to automatically select the join order optimization algorithm based on the number of tables involved. query_plan_optimize_join_order_algorithm = auto will configure DPsize for up to 9 relations and greedy for 10 or more relations.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c1ef61c]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
01785_pmj_lc_bug FAIL cidb
01064_incremental_streaming_from_2_src_with_feedback FAIL cidb
01866_view_persist_settings FAIL cidb
01710_normal_projection_join_plan_fix FAIL cidb
02552_inner_join_with_where_true FAIL cidb
03223_analyzer_with_cube_fuzz FAIL cidb
02995_new_settings_history FAIL cidb
03832_array_join_filter_push_down_cross_join FAIL cidb
04305_storage_join_composite_keys FAIL cidb
03927_anti_join_swap_tables FAIL cidb
534 more test cases not shown
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED
Build (arm_msan) DROPPED

AI Review

Summary

This PR adds auto to query_plan_optimize_join_order_algorithm and makes it the default, selecting DPsize up to 9 relations and greedy for 10 or more. I cannot approve the current version because the new default can route ordinary outer or disconnected join graphs into DPsize without a greedy fallback, producing an exception for queries that previously worked.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:875] The new default auto must preserve valid join execution for supported join graphs, but for graphs with up to 9 relations this line maps auto to a single DPSIZE attempt. solveDPsize still skips non-Inner join candidates and returns nullptr; then solve raises EXPERIMENTAL_FEATURE_ERROR instead of falling back to greedy. A plain two-table LEFT JOIN under default settings follows the same path that the test at tests/queries/0_stateless/03733_join_order_dp.sql:395 expects to fail for explicit query_plan_optimize_join_order_algorithm = 'dpsize'.
    Suggested fix: make auto include a GREEDY fallback for any case where DPSIZE cannot produce a plan, e.g. map small graphs to DPSIZE, GREEDY, or select GREEDY for non-inner/disconnected graphs before constructing JoinOrderOptimizer.

⚠️ Majors

  • [src/Core/Settings.cpp:8194] Changing the default of query_plan_optimize_join_order_algorithm from greedy to auto is a compatibility-visible setting change, but src/Core/SettingsChangesHistory.cpp:310 still records the setting as greedy -> greedy. As a result, compatibility cannot restore the previous default for older compatibility modes.
    Suggested fix: add the current-version settings-history entry with previous value greedy and new value auto, with a reason that explains the default join-order algorithm change.
Tests
  • ⚠️ Please add a focused stateless regression that leaves query_plan_optimize_join_order_algorithm at its default, or sets it explicitly to auto, and verifies a small LEFT JOIN/disconnected join graph succeeds. The current test only proves that explicit dpsize fails and dpsize,greedy succeeds; it does not cover the new default contract.
Final Verdict

Status: ❌ Block

Minimum required actions: preserve greedy fallback behavior for auto, add the missing SettingsChangesHistory entry, and cover the default/auto outer-join path with a focused test.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 18, 2026
Comment thread src/Core/Settings.cpp Outdated
Specifies which JOIN order algorithms to attempt during query plan optimization. The following algorithms are available:
- 'greedy' - basic greedy algorithm - works fast but might not produce the best join order
- 'dpsize' - implements DPsize algorithm currently only for Inner joins - considers all possible join orders and finds the most optimal one but might be slow for queries with many tables and join predicates.
- 'auto' - uses DPsize for up to 9 relations and greedy for 10 or more relations.

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.

Let's switch the default to auto. To do that, we'll also need to add an entry to src/Core/SettingsChangesHistory.cpp.

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.

Note the existing setting query_plan_optimize_join_order_limit. I think we should retire it in this PR. This can be done by moving it to the "obsolete" section (grep MARK_OBSOLETE in this file).

At the same time, we don't want to hard-code the DPSize --> greedy threshold, this should be controlled by a new setting, e.g. join_order_auto_algorithm_greedy_threshold.

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.

There should be no such parameter (auto) for the optimizer and then decide based on a threshold ( # rels < 10: pick DPSize otherwise Greedy). In query optimization jargon we call this "fall-of-the-cliff" approach and this is the approach taken e.g., by POSTGRES. If they see that the number of relations is less than 12, they pick DP, otherwise switch to a genetic based opt. alg.
The query optimizer should try to solve the problem exactly, and adaptively tune down the result quality if optimality can no longer be guaranteed, i.e., by means of query graph linearization.

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.

Fine by me. The auto would basically be a dpsize with cliff. There is a linearization like approach implemented on the layer above the join order optimization algorithms which is controlled by query_plan_optimize_join_order_limit.

@fkastrati fkastrati Jun 16, 2026 •

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 idea is to try and understand the complexity of the query graph a-priori, but not base the decision on a threshold like query_plan_optimize_join_order_limit. If the number of ccps entails that the problem can be solved exactly (optimally) we do so, if not, we linearize the query graph topology into a chain, so that we can still invoke an optimal algorithm (e.g., DPHyp), as the problem is reduced to a simpler one thus it becomes tractable. As an example we can solve optimally chain queries even up to 100 relations. If we were to work by means of thresholds, we would fall-off the cliff already for joins containing only 10 relations and thus leave a large margin on the optimization potential unharvested.

Comment thread src/Core/Joins.h Resolved
Comment thread src/Core/tests/gtest_settings.cpp Resolved
: query_graph(std::move(query_graph_))
, enabled_algorithms(enabled_algorithms_)
{
bool has_auto_algorithm = std::find(enabled_algorithms.begin(), enabled_algorithms.end(), JoinOrderAlgorithm::AUTO) != enabled_algorithms.end();

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'm not sure I understand the change in this ctor. We can probably remove the code and no bad things will happen.


for (const auto & algorithm : enabled_algorithms)
{
chassert(algorithm != JoinOrderAlgorithm::AUTO);

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.

Not needed, l. 280 does the trick.

@rschu1ze rschu1ze self-assigned this Apr 1, 2026
@clickhouse-gh

This comment was marked as resolved.

for (JoinOrderAlgorithm algorithm : optimization_settings.query_plan_optimize_join_order_algorithm)
{
if (algorithm == JoinOrderAlgorithm::AUTO)
algorithm = query_graph.relation_stats.size() > 9 ? JoinOrderAlgorithm::GREEDY : JoinOrderAlgorithm::DPSIZE;

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.

auto now becomes the default setting value, but this mapping turns it into a single DPSIZE attempt for every join graph with up to 9 relations. solveDPsize still skips all non-Inner candidates and returns nullptr; with no GREEDY fallback, solve raises EXPERIMENTAL_FEATURE_ERROR. A plain two-table LEFT JOIN under default settings will therefore fail the same way the test at tests/queries/0_stateless/03733_join_order_dp.sql:395 expects for explicit query_plan_optimize_join_order_algorithm = 'dpsize'.

Please make auto keep a GREEDY fallback for cases where DPSIZE cannot produce a plan (for example map up to 9 relations to DPSIZE, GREEDY, or select GREEDY for non-inner/disconnected graphs) before making it the default.

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 bot is right, we need to keep GREEDY for < 9 tables when there are non-inner joins.

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

Can you merge from master once more, please?

Comment thread src/Core/Settings.cpp
DECLARE(JoinOrderAlgorithm, query_plan_optimize_join_order_algorithm, "greedy", R"(
DECLARE(JoinOrderAlgorithm, query_plan_optimize_join_order_algorithm, "auto", R"(
Specifies which JOIN order algorithms to attempt during query plan optimization. The following algorithms are available:
- 'auto' - uses DPsize for up to 9 relations and greedy for 10 or more relations.

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.

Let's just say that the choice is made automatically without specifying how:

'auto' - Choose an optimal join order algorithm automatically.

While at it, can you also change the next two lines?

'greedy' - Greedy join order algorithm. Converges fast but might produce a sub-optimal join order. Can be used for queries with many joined tables.
'dpsize' - DPsize join order algorithm. Only for INNER joins. Enumerates all possible join orders (slow) and finds the most optimal one. Recommended only for queries with few joined tables.

Comment thread src/Core/Settings.cpp
Allow to use hive partitioning with S3Queue/AzureQueue engines
)", EXPERIMENTAL) \
DECLARE(JoinOrderAlgorithm, query_plan_optimize_join_order_algorithm, "greedy", R"(
DECLARE(JoinOrderAlgorithm, query_plan_optimize_join_order_algorithm, "auto", R"(

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 new default setting value must also be reflected in src/Core/SettingsChangesHistory.cpp.

for (JoinOrderAlgorithm algorithm : optimization_settings.query_plan_optimize_join_order_algorithm)
{
if (algorithm == JoinOrderAlgorithm::AUTO)
algorithm = query_graph.relation_stats.size() > 9 ? JoinOrderAlgorithm::GREEDY : JoinOrderAlgorithm::DPSIZE;

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 bot is right, we need to keep GREEDY for < 9 tables when there are non-inner joins.

AND T4.D_LookupCode = 'Lookup S'
SETTINGS query_plan_optimize_join_order_algorithm = 'dpsize';

SELECT '=========================================';

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 think below tests are a bit complex. Maybe each join algorithm can just print a line into the database log file (something like TRACE_DEBUG(log, "Optimizing join order using DPSub")). Then the test can check that this line exists in the logs using system.text_log).

@fkastrati fkastrati self-assigned this Jun 16, 2026
@fkastrati
fkastrati self-requested a review June 16, 2026 12:04
@fkastrati fkastrati closed this Jun 16, 2026
@cv4g

cv4g commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Superseeded by #107351. See #99884 (comment)

@rschu1ze

Copy link
Copy Markdown
Member

@fkastrati Thinking about this, I think an auto mode will still be a useful default for the heuristics you described in #99884 (comment). The setting can then be overridden explicitly by users with a non-auto, concrete algorithms (in case the user think he/she knows better). This will also be useful for testing.

@fkastrati

fkastrati commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

@rschulze My goal/intention was that in the default (auto) mode, the optimizer itself chooses the strategy:

  1. Try to solve the plan directly.
  2. If that is not feasible, linearize the search space and retry step 1.
  3. If that still fails, fall back to greedy().

Since this is the intended behavior, then exposing query_plan_optimize_join_order_algorithm = 'auto' seems somewhat redundant, since it simply represents the optimizer's built-in decision process. At the same time, advanced users

who know what they are doing

could still override the default and select a specific algorithm explicitly, e.g.

query_plan_optimize_join_order_algorithm = 'dpsize'

More generally, dphyp is strictly superior to both dpsize and dpsub: it achieves the theoretical minimum number of enumerated CSG/CMP pairs, resulting in better performance and it supports hyperedges, which the other two algorithms cannot handle.

Because of this, I would not expect users to choose dpsize or dpsub in production once dphyp is available. Keeping them exposed may still be useful for internal purposes such as debugging, benchmarking, and regression testing.

@rschu1ze

rschu1ze commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

My goal/intention was that in the default (auto) mode, the optimizer itself chooses the strategy:

I agree with you. However, as of today, auto is not the default setting value, this setting value does not even exist (see query_plan_optimize_join_order_algorithm in src/Core/Settings.cpp). The default is greedy. Therefore, my proposal is to introduce auto (that does what you describe) and re-purpose the existing setting values greedy and dpsize so that they don't "silently" switch to another algorithm. The latter will be useful for testing and for advanced users.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants