Skip to content

Cascades cost-based optimizer for distributed query plans - #86353

Merged
davenger merged 431 commits into
masterfrom
wip_cascades
Aug 18, 2026
Merged

davenger merged 431 commits into
masterfrom
wip_cascades

Conversation

@davenger

@davenger davenger commented Aug 28, 2025 •

Copy link
Copy Markdown
Member

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:

  • Join strategies: shuffle hash join, broadcast hash join (with 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; ANY joins are excluded because the kept row depends on the build order), local join.
  • Aggregation strategies: two-phase (partial + merge), shuffle by group keys, local; distributed_aggregation_memory_efficient and distributed_plan_force_shuffle_aggregation are honored.
  • Top-N: two-stage distributed top-N (per-node bounded sort, sorted-merge gather, coordinator limit); disabled under exact_rows_before_limit, which needs the full row count.
  • Read strategies: parallel N-way read, replicated read, local read. For FINAL, Support FINAL reads in distributed query plans (make_distributed_plan) #108148 (already in master) taught the rule-based distributed plan to split a FINAL read into disjoint primary-key-range buckets where that is safe; Cascades now reuses that machinery, so FINAL no longer forces a serial read here either. The coordinator ships each bucket's marks in the read_bucket task parameters.
  • IN (subquery): follows the rewrite_in_to_join setting 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.
  • Properties and enforcers: distribution (node count, replication, partitioning columns with equivalence classes and the types the keys are cast to before hashing) and sorting; when a plan alternative lacks a required property, an enforcer inserts the step that provides it (Gather/Shuffle/Broadcast/ScatterExchange, Sort).
  • Transformations: join commutativity (only for semantics-preserving joins: INNER ALL, CROSS, SEMI/ANY/ANTI; never ASOF, and never ANY under join_any_take_last_row), two-phase aggregation split, two-stage top-N split.
  • Cost model: work, network, and sequential components, 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_hash shards 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:

Query Rule-based -> Cascades What changed in the plan
Q21 7.66 s -> 5.34 s The four supplier x nation joins compute their small results once and broadcast them, so lineitem is not shuffled to meet them.
Q09 4.07 s -> 2.47 s part and nation are read in full by every node, so lineitem and supplier are not shuffled to meet them.
Q08 2.39 s -> 0.99 s nation x region (5 rows) is recomputed by every node; part is read in full per node, so lineitem is not shuffled to join it.
Q02 2.14 s -> 0.84 s The supplier x nation x region chain is recomputed by every node, so only partsupp and supplier are shuffled. The top-100 sort becomes two-stage, sending at most 100 rows per node.
Q05 2.05 s -> 1.12 s The whole dimension side (orders x customer x nation x region) is recomputed by every node over full local reads; lineitem joins it in place with no shuffle at all.
Q17 2.72 s -> 1.78 s The small per-part average is broadcast to every node, so the outer 600M-row lineitem read is not shuffled.
Q11 0.49 s -> 0.26 s supplier x nation is computed once and broadcast; partsupp joins it in place.
Q12 0.76 s -> 0.59 s The filtered lineitem rows (~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 their INs 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 by x 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 the IN form, and set-filter selectivity from the subquery's output estimate.

EXPLAIN pretty = 1, estimates = 1 shows 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 FINAL layer split no longer depends on the coordinator's core count, and a many-partition FINAL split 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 = 1 runs the stages in-process without it:

SET enable_cascades_optimizer = 1, make_distributed_plan = 1;

For tests, param__internal_cascades_cluster_node_count overrides the cluster size, param__internal_cascades_cost_config overrides the cost model configuration, param__internal_join_table_stat_hints injects table statistics, param__internal_cascades_task_limit lowers the task budget (it can never raise it).

Related: #106020

Changelog category (leave one):

  • Experimental Feature

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 = 1 together with make_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

  • Documentation written in /docs

Version info

  • Merged into: 26.8.1.1593 (included in 26.8 and later)

@davenger
davenger marked this pull request as draft August 28, 2025 11:27
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8a0aa0e]

Summary: ✅


AI Review

Summary

This PR adds an experimental Cascades cost-based optimizer for distributed plans and extends the distributed FINAL read path. The overall direction is sound, but the current head still has several real correctness and compatibility holes in plan serialization, Cascades support-gating, task routing, and statistics/costing, so it is not ready to merge as-is.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/AggregatingStep.cpp:1184, src/Processors/QueryPlan/UnionStep.cpp:227] The new version-8 step payloads are still emitted on downgraded plan streams. Connection::sendQueryPlan and QueryPlan::serialize send min(remote, local) as the stream version, but AggregatingStep still allows its in-order payload below version 8 and UnionStep writes allow_narrowing unconditionally. A newer initiator talking to an older shard can therefore still desynchronize the fragment stream for ordinary serialize_query_plan = 1 traffic.
    Suggested fix: gate both payloads on the actual feature version (ctx.version >= 8) or fail closed for these step shapes below version 8.
  • [src/Processors/QueryPlan/Optimizations/Cascades/Rules/DefaultImplementation.cpp:45, src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:261, src/Processors/QueryPlan/SortingStep.cpp:808] The Cascades support gate still lets plan shapes through that the best-plan extractor cannot reconstruct. DefaultImplementation still admits JoinStepLogicalLookup, which has no clone/serialization support, and SortingStep::clone still throws on partitioned full sorts while checkStepSupportedByCascades rejects only non-Full sorts. Queries with lookup joins or window-partition sorts can still get partway through Cascades and then fail with NOT_IMPLEMENTED instead of being rejected up front.
    Suggested fix: reject JoinStepLogicalLookup and partitioned SortingSteps before memo construction, or teach clone to preserve those step shapes.
  • [src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:1265] Replicating a single-shard child still assumes one flat task-parameter namespace for the whole fragment. If the replicated child already contains an exchange receiver, stripping its read-bucket keys lets the later merge overwrite that receiver’s bucket_id with the outer task routing, so the inner receive subscribes to the wrong exchange stream IDs. That is a rows-lost / wait-forever failure mode, not just a planning inefficiency.
    Suggested fix: namespace task parameters per step/receiver, or narrow replication so it cannot wrap fragments that already consume bucketed exchange parameters.
  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:6121] The new distributed FINAL bucketing logic removed the old hard per-task lane bound and replaced it with a soft target. A many-partition FINAL can still pack hundreds of merge lanes into one worker task, and buildDistributedFinalPipe materializes one merge pipe per lane, so the “distributed” plan can explode processor count and memory inside a single task instead of failing closed back to a serial read.
    Suggested fix: keep a hard lanes_per_task cap, or abort bucketing once the computed lane count exceeds the safe ceiling.

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:355, src/Processors/QueryPlan/Optimizations/Cascades/Statistics.cpp:310, src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:699] The read-statistics path still breaks two core invariants. After row-count clamps from relation/cardinality hints, NDVs are not clamped back to <= estimated_row_count, and a table-level avg_row_bytes hint still overwrites the already-projected column widths with the full-table width. That makes equality predicates look much rarer than any input allows and makes narrow projections look as expensive to move as full-row reads.
    Suggested fix: cap every num_distinct_values by the final row estimate after all clamps, and derive estimated_bytes_per_row from the projected column widths once fillReadColumnWidths has scaled the hint to the output columns.
  • [src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:99, src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:593, src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:631, src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:683] StatisticsDerivation still treats several non-row-preserving operators as if they preserved the child cardinality: the default unary fallback copies stats unchanged (OffsetStep), ExpressionStep still assumes arrayJoin is row-preserving, keyless aggregation on empty input is forced to zero rows, GROUPING SETS are modeled as one plain grouping, and LimitStep ignores offset, LIMIT 0, and WITH TIES. Those errors feed straight into join, exchange, and top-N costing.
    Suggested fix: use step traits for the generic unary fallback, special-case keyless / GROUPING SETS aggregation, and model LimitStep as offset + limit / WITH TIES instead of plain min(rows, limit).
  • [src/Processors/QueryPlan/Optimizations/Cascades/Rules/AggregationImplementations.cpp:157, src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:605, src/Processors/QueryPlan/Optimizations/Cascades/Cost.cpp:218] The partial-aggregation alternative is still costed with the same shared group statistics as the final merged aggregation, even though the partial result can contain one copy of each group per worker. The gather/merge input is therefore underpriced by up to the worker count on low-NDV keys, biasing the optimizer toward two-stage aggregation exactly where it should be most cautious.
    Suggested fix: give PartialAggregationStrategy its own physical row estimate, or correct the merge/gather cost path explicitly for replicated partial groups.
  • [src/Processors/QueryPlan/Optimizations/Cascades/OptimizerContext.cpp:132] Same-group best-cost pruning still returns before recording the candidate cost. Later fallback selection only rescans costed physical_expressions, so a pruned exact-shape alternative can disappear entirely once a cheaper over-providing enforcer occupies the best-implementation bucket. That makes the memo search incomplete even without hitting the global task budget.
    Suggested fix: record the candidate cost before pruning, or keep a separate costed fallback set that survives best-bucket pruning.
  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1228] The discovery-service worker path still calls resolveWorkerAddress(endpoint.host, endpoint.port, 0, context), so the initiator discards any worker-specific streaming-exchange port and falls back to the server-level default. If leased workers expose different exchange ports, streaming exchanges connect to the wrong endpoint even though task leasing itself succeeded.
    Suggested fix: propagate the worker’s actual streaming-exchange port through the discovery allocation API, or reject discovery-backed streaming exchanges until that metadata exists.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.80% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 3090/3496 (88.39%) · 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 28, 2025
@novikd novikd self-assigned this Aug 28, 2025
@davenger
davenger force-pushed the wip_cascades branch 4 times, most recently from 93e80b7 to a1adacb Compare September 29, 2025 13:31
@davenger
davenger force-pushed the wip_cascades branch 5 times, most recently from db6af7f to 4540f70 Compare November 20, 2025 17:38
@davenger
davenger requested a review from Copilot November 25, 2025 08:25

This comment was marked as outdated.

@clickhouse-gh

clickhouse-gh Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor

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.

davenger and others added 3 commits August 17, 2026 09:35
… 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 novikd 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, 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]>
@davenger
davenger enabled auto-merge August 17, 2026 20:33
@davenger
davenger added this pull request to the merge queue Aug 17, 2026
@davenger
davenger removed this pull request from the merge queue due to a manual request Aug 17, 2026
@davenger
davenger added this pull request to the merge queue Aug 18, 2026
Merged via the queue into master with commit caaf8da Aug 18, 2026
706 of 712 checks passed
@davenger
davenger deleted the wip_cascades branch August 18, 2026 02:23
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 18, 2026
@ylw510

ylw510 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Just noticed it. Great work!

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 18, 2026
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.
evillique pushed a commit to jh0x/ClickHouse that referenced this pull request Aug 18, 2026
…ture

Restructure the Cascades optimizer code following the review of ClickHouse#86353
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 21, 2026
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]>
alexey-milovidov pushed a commit to groeneai/ClickHouse that referenced this pull request Aug 22, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Sep 13, 2026
`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.
alexey-milovidov added a commit that referenced this pull request Sep 13, 2026
`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.
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-experimental Experimental Feature 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.

6 participants