Repository navigation
Cascades cost-based optimizer for distributed query plans - #86353
Conversation
|
Workflow [PR], commit [8a0aa0e] Summary: ✅
AI ReviewSummaryThis PR adds an experimental Cascades cost-based optimizer for distributed plans and extends the distributed Findings❌ Blockers
Final Verdict❌ Changes requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 3090/3496 (88.39%) · Uncovered code |
93e80b7 to
a1adacb
Compare
e95aab4 to
9e9570b
Compare
c2d1b88 to
eddeb46
Compare
db6af7f to
4540f70
Compare
235bb75 to
66f0f33
Compare
|
Dear @davenger, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message. |
Co-Authored-By: Claude Fable 5 <[email protected]>
…TS and overflow rows Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
… from comparison chains and pushdown puts them on both join inputs Co-Authored-By: Claude Fable 5 <[email protected]>
…ted domain, so the `EXISTS` subplans carry `Distinct` around the exchanges Co-Authored-By: Claude Fable 5 <[email protected]>
novikd
left a comment
There was a problem hiding this comment.
In general LGTM, all the review comments can be fixed in follow up PRs (this one is already too big)
…serts the derived `indexHint` filter shape Co-Authored-By: Claude Fable 5 <[email protected]>
|
Just noticed it. Great work! |
Resolves the sole conflict in `joinOrder.h`: master added `avg_row_bytes` to `RelationStats` while this branch added `estimated_rows_upper` and `estimated_rows_is_lower_bound`. The additions are independent, so all three fields are kept. Master's Cascades merge (ClickHouse#86353) and the row-estimate commits around it auto-merged into `optimizeJoin.cpp`. The swap gate still keys on `estimated_rows_is_lower_bound` rather than a source allow-list, and `relation_infos` still carries the bit to the gate. Verified on the merged tree (build id 9755a533de7390e6): test 04726_join_build_side_row_upper_bound matches its reference, and the build-side arm still discriminates - a forced `query_plan_join_swap_table = true` returns 0 where `'auto'` returns 1.
…ture Restructure the Cascades optimizer code following the review of ClickHouse#86353
Resolves one conflict in convertJoinToIn.cpp. Both sides had added the same forwarded-column resolution guard: ours in af965a0 ("Decline the JOIN to IN conversion when a key consumes a needed left column"), and master's via @ Shaohua Wang's eb95629, which fixes NOT_FOUND_COLUMN_IN_BLOCK for an arrayJoin JOIN key. The two compute the same thing; master's form hoists the sub-DAG and the input header into locals and documents why hasArrayJoin cannot gate the check, so the merged tree keeps master's version and drops our duplicate. Normalising both blocks for whitespace, comments and local names leaves only that hoisting as the difference. All six declines this branch adds are intact after the merge: the Semi-only strictness gate, the inner-or-left kind gate, the algorithm-priority walk, the join and transfer limit checks, the prepared-right-side check, and the dynamic structure key check. Every type and function they depend on still exists in master, and convertJoinToIn is still registered in the optimization list after the cascades optimizer landed in ClickHouse#86353. The Settings.cpp hunk auto-merged and remains a single doc-string line; the default of query_plan_convert_join_to_in is unchanged, so no SettingsChangesHistory entry is required. Co-Authored-By: Claude Fable 5 <[email protected]>
…4752-593c Refresh a five-day-old branch and re-run CI: the previous run lost seven jobs in GitHub's `Set up job` step (codeload 429/502), so they never executed. `optimizeJoin.cpp` and `JoinExpressionActions.cpp` are byte-identical between master `6ae413899fc` and the tree the fix was last verified on, and the merged `optimizeJoin.cpp` is byte-identical to the built and tested file, so the Cascades work merged meanwhile (ClickHouse#86353) does not disturb this change. Co-Authored-By: Claude Fable 5 <[email protected]>
`04869_distributed_plan_partial_aggregation_bucket_order` fails
reproducibly on this backport: the planner picks `Shuffle` instead of
partial aggregation plus a memory-efficient merge, so the `EXPLAIN`
prints `GatherExchange / Aggregating / ShuffleExchange` where the
reference has `MergingAggregated (merge) / GatherExchange /
Aggregating (partial)` - and the test never reaches the code this
pull request fixes.
The distributed rewrites run post-order, so `tryMakeDistributedRead`
has already inserted a `GatherExchangeStep` above the read by the time
`tryMakeDistributedAggregation` calls `estimateReadRowsCount`. With
the estimation unable to look through an exchange it returns no stats
at all, and the strategy falls back to `Shuffle` "to be safe". The
row-count hint never reaches the read step, which is why lowering
`cardinality` did not help.
`0fae364ef698` ("Make row count estimation look through exchange steps
in non-cloud builds") is a commit of this very pull request and it
removed those two `CLICKHOUSE_CLOUD` guards. It was lost from the
backport: PR #86353 (Cascades) removed the same guards on `master`
three days before #114523 merged, so by merge time the hunk was a
no-op in the pull request's net diff, and the backport carries only
that net diff. `master` and `26.8` have no `CLICKHOUSE_CLOUD` left in
this file; this branch still had both guards.
The guarded include is dropped rather than unguarded, because the
same header is already included unguarded further down, which leaves
this file exactly as `master` has it.
`04869_distributed_plan_partial_aggregation_bucket_order` fails
reproducibly on this backport: the planner picks `Shuffle` instead of
partial aggregation plus a memory-efficient merge, so the `EXPLAIN`
prints `GatherExchange / Aggregating / ShuffleExchange` where the
reference has `MergingAggregated (merge) / GatherExchange /
Aggregating (partial)` - and the test never reaches the code this
pull request fixes.
The distributed rewrites run post-order, so `tryMakeDistributedRead`
has already inserted a `GatherExchangeStep` above the read by the time
`tryMakeDistributedAggregation` calls `estimateReadRowsCount`. With
the estimation unable to look through an exchange it returns no stats
at all, and the strategy falls back to `Shuffle` "to be safe". The
row-count hint never reaches the read step, which is why lowering
`cardinality` did not help.
`0fae364ef698` ("Make row count estimation look through exchange steps
in non-cloud builds") is a commit of this very pull request and it
removed those two `CLICKHOUSE_CLOUD` guards. It was lost from the
backport: PR #86353 (Cascades) removed the same guards on `master`
three days before #114523 merged, so by merge time the hunk was a
no-op in the pull request's net diff, and the backport carries only
that net diff. `master` and `26.8` have no `CLICKHOUSE_CLOUD` left in
this file; this branch still had both guards.
The guarded include is dropped rather than unguarded, because the
same header is already included unguarded further down, which leaves
this file exactly as `master` has it.
A Cascades-style cost-based optimizer that chooses distribution strategies for the multi-stage distributed query plans of #106020. It explores alternatives in a memo (a shared store of equivalent plan fragments) with top-down, goal-directed search and picks the cheapest plan satisfying the required distribution and sorting properties, inserting exchange operators (plan steps that move rows between nodes) as needed.
Implemented:
ReplicatedRead— every worker repeats the same read of a small table instead of a network broadcast, assuming shared storage where all workers see the same data), replicated join (a small deterministic join is recomputed identically on every node over such reads, so its result never crosses the network; nested joins compose;ANYjoins are excluded because the kept row depends on the build order), local join.distributed_aggregation_memory_efficientanddistributed_plan_force_shuffle_aggregationare honored.exact_rows_before_limit, which needs the full row count.FINAL, Support FINAL reads in distributed query plans (make_distributed_plan) #108148 (already in master) taught the rule-based distributed plan to split aFINALread into disjoint primary-key-range buckets where that is safe; Cascades now reuses that machinery, soFINALno longer forces a serial read here either. The coordinator ships each bucket's marks in theread_buckettask parameters.IN (subquery): follows therewrite_in_to_joinsetting like the rest of the planner (the forced join form is removed). In the default set form the set-building subqueries are planned separately and distributed like any other query.Gather/Shuffle/Broadcast/ScatterExchange,Sort).INNER ALL,CROSS,SEMI/ANY/ANTI; neverASOF, and neverANYunderjoin_any_take_last_row), two-phase aggregation split, two-stage top-N split.work,network, andsequentialcomponents, each priced as wall-clock per node: a shuffle moves 1/N of the data per node, a broadcast payload is ingested once by every receiver in parallel, and a gather funnels every row through one endpoint, so its transfer stays undivided and pays a per-row cost. A hash-table build counts as parallel work (parallel_hashshards it across threads); a fixed per-exchange overhead keeps small inputs local. A table read is priced on its scan volume - the rows the primary key keeps - not on its output estimate, so a filter off the sorting key cannot make a replicated re-read look free. Standalone filters (e.g.HAVING) are estimated from column NDVs with join-key equivalence classes; join estimates are clamped to join kind and strictness semantics; exchange costs use per-row byte widths measured from the parts' column sizes (followed through renames, not derived from types). All weights and calibration constants are overridable at query time.What this improves over the rule-based distributed planner, on TPC-H plans. The rule-based planner broadcasts a small table when its read is below
distributed_plan_max_rows_to_broadcast, but it often cannot size the result of a join, so a small join result (nation x region, 5 rows after the region filter) is scattered across nodes, joined there, and shuffled again (repartitioned across nodes) by the next join key. It also often inserts a shuffle at join and aggregation boundaries even when the rows are already divided by the right key. Cascades estimates sizes through joins, knows which partitioning already holds, compares broadcast against shuffle by cost for each join, and recomputes a small deterministic join on every node when that is cheaper than moving its result. On TPC-H SF100 over 8 nodes (same binary, same run window; times are server-side means of the hot runs) the join-heavy queries improve:supplier x nationjoins compute their small results once and broadcast them, solineitemis not shuffled to meet them.partandnationare read in full by every node, solineitemandsupplierare not shuffled to meet them.nation x region(5 rows) is recomputed by every node;partis read in full per node, solineitemis not shuffled to join it.supplier x nation x regionchain is recomputed by every node, so onlypartsuppandsupplierare shuffled. The top-100 sort becomes two-stage, sending at most 100 rows per node.orders x customer x nation x region) is recomputed by every node over full local reads;lineitemjoins it in place with no shuffle at all.lineitemread is not shuffled.supplier x nationis computed once and broadcast;partsuppjoins it in place.lineitemrows (~30K of 600M) are gathered once and broadcast; nothing is shuffled.The remaining queries change less. Summed over all 22 queries, hot server time drops from 36.8 s to 28.8 s (about 22% lower). The remaining regressions are the
IN (subquery)queries Q18 (2.43 s -> 2.85 s) and Q20 (2.24 s -> 2.99 s). With the forced join rewrite removed, both run theirINs as sets in both modes, and the sets built are identical; the difference is in the plans around them. Cascades picks replicated-read shapes that rescan moderate tables on every node, which loses here for a structural reason: the main reads are filtered byx IN <set>, and the set contents do not exist at costing time, so the model cannot credit a shuffle-based plan for how few rows survive the set filter, while the replicated read's full scan is paid regardless. Two follow-ups: a cost-informed choice of theINform, and set-filter selectivity from the subquery's output estimate.EXPLAIN pretty = 1, estimates = 1shows the chosen plan with a row estimate and the accumulated cost for each step.Also in this PR, two improvements to the shared bucketed-read machinery (they benefit the rule-based path too): the
FINALlayer split no longer depends on the coordinator's core count, and a many-partitionFINALsplit groups its layers into the target task count instead of falling back to a serial read.Design, a worked example on TPC-H data (a simplified 3-table query traced through the memo), and current limitations are documented in
src/Processors/QueryPlan/Optimizations/Cascades/ARCHITECTURE.md. Plan-shape tests cover the actual TPC-H queries (03836_tpch_join_order_plans), and focused tests pin the cost-model contracts (e.g.04869_cascades_read_cost_granule_volume,04838_cascades_filter_selectivity).Disabled by default. Requires the analyzer; remote execution requires the stateless-worker configuration, while
distributed_plan_execute_locally = 1runs the stages in-process without it:For tests,
param__internal_cascades_cluster_node_countoverrides the cluster size,param__internal_cascades_cost_configoverrides the cost model configuration,param__internal_join_table_stat_hintsinjects table statistics,param__internal_cascades_task_limitlowers the task budget (it can never raise it).Related: #106020
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added an experimental Cascades cost-based optimizer for distributed query plans, enabled by
enable_cascades_optimizer = 1together withmake_distributed_plan = 1. It chooses between shuffle, broadcast, replicated, and local join strategies, two-phase, shuffle, and local aggregation, two-stage distributed top-N, and parallel and replicated reads by estimated cost, inserting exchange operators as needed.Documentation entry for user-facing changes
Version info
26.8.1.1593(included in26.8and later)