Repository navigation
Make DPsub the default join order algorithm, with the CD-C conflict detector - #120110
Conversation
|
Workflow [PR], commit [2d88384] Summary: ❌
AI ReviewSummaryThe PR makes Findings❌ Blockers
Missing context / blind spots
Final Verdict |
f089830 to
cc10270
Compare
…ults by DPSub are nevertheless correct.
Two conflicts, both from master reorganizing around our changes: - `optimizeJoin.cpp`: master dropped the `AggregatingStep` and `CommonSubplanReferenceStep` includes along with the code that used them, and moved `joinOrder.h` into its sorted block. Kept master's block and added `joinOrderAlgorithms.h` to it, which we need for `DPSUB_MAX_RELATIONS`. - `05054_cascades_aggregation_pushdown_join_subtree.sql`: master removed the old-analyzer test mode and with it the whole tag line, while we had added `no-random-settings` to it. Kept `no-random-settings` and dropped the obsolete `no-old-analyzer`.
Master moved the release to 26.10, so the two defaults this change flips have to be recorded there: the settings history is keyed on the version that ships the change, and `compatibility` reads it to hand back the older value. The 26.9 block goes back to what it says on master. It records what 26.9 shipped, which is `query_plan_optimize_join_order_use_conflict_detector_c` still off - our flipping it to on belongs to 26.10, not to a release that already went out.
The test proves that a satisfied `LIMIT` stops the stages upstream of it, using a scan that sleeps a second per block: if the stop signal does not reach it, the scan runs on and `max_execution_time` aborts the query. That only works while the sleeping scan sits on the probe side of the top join. A hash join reads its whole build side before it emits a row, so a sleeping scan placed there cannot be stopped by a `LIMIT` above it. The test already guards the one route it knew about, `query_plan_join_swap_table`, but `dpsub` gets there by a different one: it reorders the join so the scan's subtree is the top join's right input, and the query times out after 25 seconds instead of finishing in 2. Pin the algorithm alongside the settings the test already pins for the join order. This test is about the stop signal crossing idle exchanges, not about which order the optimizer picks.
| 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, "dpsub,greedy", R"( |
There was a problem hiding this comment.
Making query_plan_optimize_join_order_algorithm = 'dpsub,greedy' the default does not look safe yet. The PR itself has to opt two queries back out of that default:
tests/queries/0_stateless/04033_tpc_ds_q82.sh:15-18forcesgreedybecause the stock 4-table TPC-DSquery_82has no stats anddpsubpicks aninventoryxstore_salesinner pair that builds billions of rows and runs out of memory.tests/queries/0_stateless/05024_distributed_plan_limit_early_stop_idle_sink.sql:30-49forcesgreedybecausedpsubmoves the sleeping scan to the build side and the query times out instead of lettingLIMITstop it.
Those are user-visible regressions of the new default, not test-only noise. I think the default needs to stay greedy until dpsub can automatically skip or fall back on these shapes, at least when the plan is being ranked on missing or imprecise stats or when the reordered build/probe choice destroys an upstream early-stop path.
There was a problem hiding this comment.
Making DPsub with CD-C the default is the purpose of this PR. The queries pinned to greedy have no statistics, which is a cardinality estimation problem rather than a join order one and is outside its scope; the expected performance changes are listed in the PR description.
…op_idle_sink The test hard-codes the exchange streams between the `LIMIT` and the sleeping scan, which follow from one join nesting. CI now injects `query_plan_optimize_join_order_algorithm`, and DPsub nests the two joins the other way round: the subtree with the sleeping scan becomes the build side of the outer hash join, so it is read to the end before the `LIMIT` sees a row and nothing is left to stop early (102 s and no stop traces, vs 3 s under `greedy`). The early-stop propagation itself is fine; the test's scenario just does not arise for that plan, so pin the algorithm next to the `query_plan_join_swap_table` pin that exists for the same reason. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106734&sha=928e9e612ed212320ad39197cf222cc47eb99cfc&name_0=PR Related: #106734 Related: #120110 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…conflict-detector # Conflicts: # src/Core/Settings.cpp # src/Core/SettingsChangesHistory.cpp # src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp # tests/queries/0_stateless/05024_distributed_plan_limit_early_stop_idle_sink.sql
A join the optimizer has already settled enters its parent's graph as a single relation, and the row count it arrived at is the only estimate that relation has. `estimateReadRowsCount` returned early for any node with two children, so the parent saw nothing and `computeJoinCost` read the missing count as one row through `value_or(1)` - the largest input in the query looked like the cheapest thing to join. Read the estimate before that check. On TPC-DS q72 the boundary is real: the non-equi predicate `inv_quantity_on_hand < cs_quantity` splits `inventory` and `catalog_sales` into their own graph, which estimates itself at 945,072,914 rows against a true 944,916,882 - 0.02% off - and the parent then planned eight relations around it as if it returned one row. With column statistics the query goes from 11.6s to 0.8s, and under `dpsub` with the CD-C conflict detector from 72.7s to 1.0s: the detector widens the search space, so a wrong estimate buys more wrong plans. Measured over the full 99-query TPC-DS suite at scale factor 1 with column statistics, no other query changes. The relation name of such a sub-join is a chain that already carries its own inputs' estimates, so it is marked composite and `EXPLAIN` no longer appends a second estimate to it. This restores #97114, reverted in #99957 for a suspected performance regression. On tables without column statistics the estimate it propagates is itself unreliable, and there the change is a wash across TPC-DS - 18 queries faster, 11 slower. #101398 proposes gating propagation on a trust flag. Related: #97114 Related: #99957 Related: #101398
…imate Both tests assert plan shapes that change once an already-optimized sub-join passes its row estimate to the parent join graph. `03837_subquery_ndv_propagation_join_order` is the direct case, and the update is the behaviour it was written to assert: the subquery input was printed as `sq[no_stats~?]` with `ResultRows: unknown`, and now carries the 50000 rows its own join settled on, which also reorders the two dimensions above it. `03836_tpch_join_order_plans` changes in 2 of its 25 plans, Q02 and Q20, both of which join through a correlated subquery. It pins `query_plan_optimize_join_order_algorithm = 'dpsize,greedy'`, so these are the estimate alone, not the `dpsub` default. The other 23 plans are unchanged.
Conflicts: `tests/clickhouse-test` keeps this branch's join-order randomization (master only dropped its smaller `query_plan_optimize_join_order_algorithm` list in #120110); `03580` and `05024` take master's new `query_plan_join_swap_table` pin and comment next to this branch's pins. #120110 makes `dpsub,greedy` with conflict detector `c` the default, and master's references now assume it, so the pins this branch added "to the default" (`'greedy'`, `''`) now pin the new defaults. Related: #106734 Related: #120110 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@fkastrati @ahmadov @rschu1ze — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
The option kept the row estimate and column statistics of an already optimized `JoinStepLogical` from reaching its parents unless a caller opted in. It was added because moving the sub-join case into `estimateDirectRelationStats` made it reachable for the first time; before, it sat behind the single-child check and never ran, so the option preserved the state after #99957 reverted #97114. #120110 then deliberately restored that propagation for every caller of `estimateReadRowsCount`. The merge with master kept the option and only opted in for join reordering, so this branch still diverged from master for all other consumers. For example, the distributed plan shuffled the right side of a join that was a small optimized sub-join instead of broadcasting it, because its row count was unknown. Drop the option so sub-join estimates propagate as on master. The `Unsupported` (and for semi/anti joins `RowSubset`) provenance stays, so consumers that gate on `ColumnStatsProvenance` still fail closed on a sub-join's column statistics.
`03623_convert_any_join_to_semi_or_anti_2`: master's reference now holds the `dpsub` estimate with the `c` conflict detector (#120110); a randomized `greedy`/`dpsize`/`dphyp` first estimates the LEFT SEMI join at the left side's cardinality. Pin the default algorithm next to the detector. `05320`, `05332`, `05394`: they assert that a TopN read populates and consults the query condition cache, which the randomized `use_query_condition_cache_for_top_k = 0` turns off by design. Pin it to 1. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106734&sha=775b5741e5dde9750a7d2a8cf7f9876b1bf42022&name_0=PR Related: #106734 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflicts of backporting #120110 to 26.10: - `joinOrderDPSub.cpp`: take the log message of #120110. - `03836_tpch_join_order_plans.reference`: regenerated on a 26.10 build with #120110; it differs from the 26.10 reference only in the plans of Q2 and Q20, the two that #120110 changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #120110 to 26.10: Make DPsub the default join order algorithm, with the CD-C conflict detector
…m, with the CD-C conflict detector
Backport #120110 to 26.10: Make DPsub the default join order algorithm, with the CD-C conflict detector
All three inputs of the test are `numbers(10)` reads, which have no row estimate, so the join graph now keeps its written join tree `(a JOIN b) JOIN c` instead of costing every input as one row. The runtime filter of the outer join is still pushed down through the inner join, now into its build side `b`, and the inner join's filter is applied to `a`. The new reference is byte-identical to the one master had before ClickHouse#120110 changed the default join order search. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…m, with the CD-C conflict detector
…dering `query_plan_merge_expression_into_join` (ClickHouse#98533) merges the projection above a child join into the reordered join graph, so a constant of that projection (`SELECT 123 AS h FROM a JOIN b`) becomes a sourceless COLUMN node of the group's DAG. When `chooseJoinOrder` rebuilt the last join of the group it appended every COLUMN output to `actions_after_join`, the columns the join itself returns; the inclusion was meant for `__join_result_dummy`. `JoinStepLogical::convertToPhysical` evaluates a sourceless node in the left pre-join actions, so the constant travelled through the join as a left column: - rows that a RIGHT, RIGHT ANTI or swapped LEFT join pads got the type default (`0`, `''`, `[]`, `NULL`) instead of the constant; - a hash join materialized the column while the logical header declares it constant: `Code: 44 ... non constant in source stream but must be constant in result (ILLEGAL_COLUMN)` for a 3-table INNER/LEFT join. ClickHouse#120110 made DPsub + the CD-C conflict detector the default, which keeps the RIGHT / RIGHT ANTI join on top for the shape in ClickHouse#131590, so it is reachable with default settings on master; 26.10.3.7 shows it with `query_plan_join_swap_table = 'true'`. Return only the dummy from the rebuilt join. Every other constant is computed by the post-join actions, the path a `materialize(123)` output already takes. When nothing but constants is returned, the existing fallback keeps one input column in the join for the row count. `JoinStepLogical::isDummyResultColumn` exposes the dummy-name check that `isDummyColumnOfThisStep` already used. Closes ClickHouse#131590 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: https://github.com/ClickHouse/clickhouse-private/issues/59564
Related: #126940
Makes DPsub the default join order algorithm and turns on the CD-C conflict detector with it, so that join reordering considers the full search space by default instead of the greedy first fit.
query_plan_optimize_join_order_algorithmbecomesdpsub,greedyandquery_plan_optimize_join_order_conflict_detectorbecomes'c'.greedystays at the end of the chain because DPsub declines query graphs it cannot optimize, andJoinOrderOptimizer::solveraises an exception.Bounding the search by table count. The budget on connected-subgraph pairs is replaced by
DPSUB_MAX_RELATIONS= 12. Measured on a debug build at 12 tables (arm-based ec2 VM machine): chain 0.52 s, star 0.61 s, clique 0.69 s. The group of tables handed to the optimizer is now kept within that limit whenever DPsub optimizes the query, so DPsub is never given a graph it would decline. Nothing changes at the defaultquery_plan_optimize_join_order_limitof 10.Semi/anti reordering under the default chain.
conflictDetectorReordersSemiAntirequired DPsub to be the only algorithm, so the new default would have silently switched it off. It now only requires DPsub, since the algorithms behind it (e.g., greedy) are reached only where DPsub declines. Such a group may still be planned by DPsub alone, as any other algorithm builds plain joins and the top join's type would then be copied onto all of them, soJoinOrderOptimizer::solveraises an exception if one ever reaches another algorithm.Two CD-C checks pinned the join order. Both demanded a join's whole ON clause at a single node, but an inner join's ON clause is split into parts that
collectJoinEdgesMaskplaces independently. Whenever an ON clause reached three or more tables, DPsub rejected every order that did not reproduce the original query and degenerated to the original tree. On a 5-way join this cost an intermediate result of 200 million rows instead of 200 thousand:computeConflictOperatorsno longer fills the required tables of a non-degenerate inner join under CD-C. CD-A keeps them, as it stores its conflicts there.isValidJoinOrderMaskConflictaccepts a split that an inner join condition spans, through the newhasInnerEdgeAcross.initDPTablenow links the two sides of every recorded join, not only the degenerate ones: a condition over three or more tables is not a two-table edge either, so the sides went unlinked and DPsub gave up on a query it can plan. This also keeps the original join order reachable at all times.DPsub gets every join the conflict detector models. With a conflict detector, the group of tables handed to the optimizer used to be cut wherever a join's null-supplying side was more than one table, so a
RIGHT,FULL,RIGHT SEMIorRIGHT ANTIjoin at the top, or aFULLjoin anywhere, split the tree into groups of two that could only be swapped. When DPsub leads the chain and a conflict detector is set, both sides of outer and semi/anti joins andFULLjoins are now flattened (isFlattenableJoinSide,isFlattenableChildJoin), and aFULLor semi/anti join at the top keeps the full group size. The ON-clause conditions of an outer join are tied to its whole null-supplying side instead of a single table (outer_join_conditionsmaps to aBitSet), and the relations of a multi-table null-supplying side are kept out of column equivalences. A graph that only the conflict detector can describe is markedrequires_conflict_detector: no other algorithm may plan it, and DPsub does not turn it down when cross products hold it together. Without a conflict detector, and for the other algorithms, nothing changes.Which side builds the hash table. The cost of a join is the same whichever way round its inputs go, so DPsub left the sides as the enumeration first reached them, often reading a whole subtree into the hash table.
buildPhysicalPlannow puts the smaller estimate on the build side, mirroringALLouter joins throughreverseJoinKind. On equal estimates, or when an input has none (e.g. aUNION ALLsubquery), the input with more tables stays on the probe side, which gives left-deep plans. This is skipped whenquery_plan_join_swap_tableis pinned, and forANY/SEMI/ANTIgroups, whose joins get their strictness only after planning and must not be turned round (QueryGraph::join_strictness); it still applies inside a group the conflict detector flattened around a semi/anti join.Join kinds in a semi/anti group. A cross product among the plain joins of a group that holds a reordered semi/anti join was reported as
INNER, becausechooseJoinOrderrestoredInnerfrom the top join's strictness rather than the join's own.Local testing on a debug build: the join order, conflict detector, semi/anti and join-plan stateless tests pass (the rest need JSON, ICU, Parquet, ZooKeeper or query-plan packets locally);
EXPLAINreferences are updated for the new default plans, and the tests asserting on a plan pinquery_plan_join_swap_table. A differential fuzzer of 2000 random queries mixing inner, outer,FULL, semi and anti joins over tables with NULL and duplicate keys returns the same results with the defaults, withdpsuband CD-C, and without reordering.05293_dpsub_conflict_detector_flattens_all_join_kindschecks that every join kind reaches DPsub as one group with unchanged results.Expected performance changes. The performance comparison runs against master, where greedy is the default, so it shows these on purpose:
query_interpretation_wide_join(+25-65%) andone_thousand_joins(about +115%). A shared column puts every table in one equivalence class, so each group of 10 tables is a clique to DPsub. That is 28501 pairs to evaluate instead of 165 for a chain, about 45 ms per group against 0.6 ms for greedy. Same-column chains of 10 or fewer tables take 2-3 ms.tpch #8, about +20%). DPsub picks an order its cost model rates cheaper than greedy's (4.16M against 4.98M at SF1), but the cost model does not account for which side builds the hash table, so the plan runs slower. Fixing the cost model is outside this PR.tpch #1-55%,tpcds #71-45%,tpch-join_algorithm-partial_merge #4-44%,tpcds #84-39%,tpcds #63(Q64) -25%.Other flagged tests (
avg,arrow_format,space_filling_curve,json_key_formatting) contain no joins.tests/performance/tpcds.xmlnow pinsuse_hash_table_stats_for_join_reordering = 0: the cached hash table sizes are measured under the previous run's plan, so they made Q64 switch between two plans on alternate runs.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
DPsub is now the default join order algorithm (
query_plan_optimize_join_order_algorithm = 'dpsub,greedy'), together with the CD-C conflict detector, which also lets semi and anti joins take part in reordering. Queries with more than 12 joined tables fall back to the greedy algorithm.Workflow [PR]
Sync PR [sync-upstream/pr/120110]
Version info
26.11.1.533-master(included in26.11and later)