Skip to content

Bound the Cascades cluster node count by the distributed-read bucket limit - #115398

Merged
davenger merged 1 commit into
ClickHouse:masterfrom
groeneai:bound-cascades-node-count-by-read-bucket-limit
Aug 21, 2026
Merged

davenger merged 1 commit into
ClickHouse:masterfrom
groeneai:bound-cascades-node-count-by-read-bucket-limit

Conversation

@groeneai

@groeneai groeneai commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Experimental Feature

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

A very large distributed_plan_workers_num no longer makes the server abort with a
std::length_error when the experimental make_distributed_plan and enable_cascades_optimizer are
enabled. Such a node count is now rejected with INVALID_SETTING_VALUE.

Description

Related: #109770

That PR capped the sibling setting the same way.

Found by AST fuzzer (arm_asan_ubsan):
CI report
(unrelated carrier PR). Reproduces deterministically:

SELECT count() FROM t
SETTINGS enable_cascades_optimizer = 1, make_distributed_plan = 1,
         distributed_plan_execute_locally = 1, distributed_plan_workers_num = 9223372036854775807;
-- std::length_error in sliceMarksAcrossBuckets; the server dies in a debug build

buildContext resolves cluster_node_count from the internal query parameter, from
distributed_plan_workers_num, or from the configured worker cluster, checking only for zero. The
ParallelRead rule passes it through as the read's bucket count, and sliceMarksAcrossBuckets sizes
a vector to it as its first statement, before the 256 ceiling already threaded in is consulted.

buildContext now also rejects a resolved count above max_distributed_read_buckets, beside the
existing zero check. Bounding the resolved value covers all three sources of the count and every
consumer of it: the read buckets, the layer budget FINAL derives from them, and the exchange fan-out
sized from the count. Not inside sliceMarksAcrossBuckets, which FINAL legitimately calls with
target_buckets * 16-derived counts before grouping the layers into at most 256 tasks.

Behaviour change: a count above 256 that did not reach the plain slicer (257, a FINAL read, or a
worker cluster above 256 replicas) is planned today and is now refused. Such a plan reads serially but
can still scatter to that many exchange destinations, which is the memory cost this same ceiling
already bounds for the sibling settings. @ davenger, say so if you would rather bound the setting
itself (a worker lease count) or clamp.

04320_distributed_plan_read_rejects.sql gains seven arms: both sources of the count, both read paths,
and three positive controls (256 accepted on the plain and FINAL paths, plus a rule-based query with
a huge workers_num untouched). It fails on unpatched master with server died, and passed 50/50
runs with the fix.


Workflow [PR]
Sync PR [sync-upstream/pr/115398]

Version info

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

…limit

The AST fuzzer found a std::length_error (server abort in debug and sanitizer
builds) reachable with make_distributed_plan, enable_cascades_optimizer and a
very large distributed_plan_workers_num:

    SELECT count() FROM t
    SETTINGS enable_cascades_optimizer = 1, make_distributed_plan = 1,
             distributed_plan_execute_locally = 1,
             distributed_plan_workers_num = 9223372036854775807;

buildContext resolves cluster_node_count from the internal query parameter,
from distributed_plan_workers_num, or from the configured worker cluster, and
checks only for zero. The ParallelRead rule passes the resolved count through as
the read's bucket count, and sliceMarksAcrossBuckets sizes a std::vector to it as
its first statement. The 256 bucket ceiling is already threaded into
setupDistributedReadBuckets and is consulted, but only after the allocation.

buildContext now also rejects a resolved count above
max_distributed_read_buckets, beside the existing zero check. Bounding the
resolved value covers all three sources of the count and every consumer of it,
including the read buckets, the layer budget the FINAL path derives from them,
and the exchange fan-out sized from the count by DistributionEnforcer.

The bound is deliberately not placed inside sliceMarksAcrossBuckets: the FINAL
path legitimately calls it with target_buckets * 16 derived counts and only
afterwards groups the resulting layers into at most 256 tasks, so a check there
would drop non-intersecting ranges while intersecting ones remained.

A count above the ceiling cannot produce a bucketed read: the read would split
into that many buckets and is then refused for exceeding the same ceiling. The
plan is not necessarily single-node, though: a serial read can still feed a
scatter or broadcast sized from the count, and a replicated read pins one bucket
while advertising the full count. Bounding the count bounds that fan-out too,
which is the memory cost the sibling cap on
distributed_plan_default_reader_bucket_count already limits with the same
ceiling, error code and test file.

One deliberate behaviour change: a count above 256 that did not reach the plain
slicer (257, a FINAL read, or a statically configured worker cluster above 256
replicas) is planned today and is now refused with INVALID_SETTING_VALUE. Such a
plan reads serially but can still scatter to that many exchange destinations, so
distributed plans are affected. No result changes silently.

04320_distributed_plan_read_rejects gains seven arms covering both sources of the
count, both read paths, and three positive controls: 256 accepted on the plain
and FINAL paths, and a rule-based query with a huge distributed_plan_workers_num
left untouched, since without Cascades the count never becomes a bucket count.
Deleting the bound makes the file abort, and widening it to reject 256 makes the
positive controls raise instead of answering, since the bound refuses rather than
falling back to a serial read.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, all findings resolved)

This PR went through an independent cold review plus a separate second-model gate on each round, with
every finding adjudicated against the code. Recorded here for transparency; nothing below is an open
question.

# Finding Verdict
❌ The regression test could not detect removal of the second guard, and the 256 positive controls could not distinguish "accepted" from "silently read serially" Agreed, fixed. The second guard turned out to be unreachable dead code: setupDistributedReadBuckets has exactly two callers, one bounded by the existing setting validator and one bounded by the new bound, and the guard's own trace line fired zero times across ~20 probe queries (with sibling early-returns in the same function captured as a positive control). It was deleted, so this PR no longer touches ReadFromMergeTree.cpp. The controls are not blind because the bound throws rather than falling back, proven by mutating > to >=: the 256 arms then raise INVALID_SETTING_VALUE instead of answering.
❌ The justification "above the ceiling only single-node plans remain" is false, and the commit message repeated it as "no query that produced a distributed plan is affected" Agreed, fixed. A refused bucketed read does not imply a single-node plan: a replicated read pins one bucket while advertising the full count, and a serial read can still feed a scatter or broadcast sized from the count. 04340_cascades_final_read.sql is the in-tree example of that shape. The comment, commit message and description now state the actual invariant, which is that the bound limits read-bucket allocation and exchange fan-out.
⚠️ The Related: relationship did not use a full GitHub URL on its own line Agreed, fixed in the description.
💡 Should 04320 carry no-darwin, since the new positive controls may execute a distributed pipeline and 17 of 29 cascades tests carry that tag? Not changed. macOS runs only the fast test, which loads ci/defs/darwin.skip; this file is not listed there, and 12 cascades tests including 04509 also lack the tag while executing a distributed read. Adding a skip on suspicion would drop real coverage. Noted, not blocking.
💡 Should the changelog category be Bug Fix to match #109770? No. enable_cascades_optimizer, without which this is unreachable, is in the unreleased 26.8 block of SettingsChangesHistory.cpp, so "misbehavior in an official stable release" would be inaccurate. #109770's setting predates it.

One round was spent on a rebase: master moved 150 commits mid-review and renamed the type the guard
reads, so the change was re-applied on the new base and every measurement below was re-taken there
rather than carried over.

Validation on the shipped tree: the bound was deleted (test aborts with the original
std::length_error, fault build id matching the mutant) and over-tightened (the 256 controls raise
instead of answering), with both restores rebuilding bit-exact. 50/50 randomized runs of 04320 pass.
A 65-test cascades + distributed_plan A/B against the unpatched base gives 0 regressions: 19
failures on each arm, all of them the same minimal-server configuration gaps (no worker cluster, no
stateless worker client). The fail sets differ by one test in each direction; both of those flip
intermittently on both arms across repeat runs, neither enables the Cascades optimizer, and the new
error message appears nowhere in either arm's log.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One query on a 200k-row MergeTree table with enable_cascades_optimizer = 1, make_distributed_plan = 1, distributed_plan_execute_locally = 1, distributed_plan_workers_num = 9223372036854775807. Aborts on the first attempt, no randomization or repeat runs needed. Kills a real server too (exit 134).
b Root cause explained? buildContext resolves cluster_node_count from the internal query parameter (priority), from distributed_plan_workers_num, or from the configured worker cluster, and checks only for zero. ParallelReadImplementation::applyImpl passes it as both node_count and target_buckets, so setupDistributedReadBuckets calls sliceMarksAcrossBuckets(parts, target_buckets), whose first statement is std::vector<RangesInDataPartsDescription> result(bucket_count) (ReadFromMergeTree.cpp:4536). The 256 ceiling is threaded in and is consulted, but at :5995, one statement too late.
c Fix matches root cause? Yes. The bound is applied to the resolved count, in buildContext, where the number becomes authoritative for the whole optimization. Not a widened bound, not a no-random-* tag, not a data reduction, not a guard at the abort site.
d Test intent preserved / new tests added? Existing 04320_distributed_plan_read_rejects arms are untouched; seven arms added to that same file, whose stated purpose is this defect class. Three of the seven are positive controls, so the file cannot pass by refusing everything. Both failure directions of the new bound are verified by mutation: deleting it makes the file abort, and tightening > to >= makes the 256 control raise instead of answering.
e Both directions demonstrated? Yes, re-measured on the shipped binary against the current base. Pre-fix (unpatched master, build id c26e0799...): clickhouse local SIGABRT rc=134, and a real server aborts, logging std::length_error through sliceMarksAcrossBuckets and setupDistributedReadBuckets on arm 1 of the new test. Post-fix (ae0d046a...): Code: 471 INVALID_SETTING_VALUE rc=215, server stays alive, test OK, 50 of 50 randomized runs pass. Reverting the bound and rebuilding restores the abort; re-applying rebuilds byte-identically, so the two arms differ only by the bound.
f Fix is general across code paths? Yes. All consumers of cluster_node_count were enumerated (grep -rn cluster_node_count src/); every one reads memo.getContext().cluster_node_count, which is set only from buildContext's return value, and the check throws before that value is ever published, so the read buckets, the target_buckets * 16 layer budget the FINAL path derives from them, and the exchange fan-out (makeDistributed.cpp:1386-1388, sized from node_count via DistributionEnforcer) are all covered. getCandidateNodeCounts can only propagate the bounded count, never amplify it. The two call sites of setupDistributedReadBuckets are also enumerated, and every path into them is bounded: makeDistributed.cpp:778 by validateDistributedPlanBucketCounts, and RuleUtils.cpp:39 by this check, reached from ParallelReadImplementation with the resolved count and from ReplicatedReadImplementation with a literal 1. Fixed at the source, not at the abort site.
g Fix generalizes across inputs (params/datatypes/wrappers)? The count is a size_t, so no type wrappers apply. Boundary matrix exercised by the new arms: 256 accepted on the plain and FINAL read paths, 257 refused, 9223372036854775807 refused on both read paths, and 9223372036854775807 via the internal query parameter refused even when the setting says 4, which pins the parameter's priority. 0 is unaffected and still gives the pre-existing SUPPORT_IS_DISABLED from the zero check the new bound sits beside; small accepted counts (1, 4) keep their existing coverage in 04515_cascades_worker_count_node_source, which the suite run below confirms is not regressed. Both sources of the count are tested, both read paths are tested, and the rule-based path is tested as a non-regression.
h Backward compatible? No setting default, wire format or serialization changes, so no SettingsChangesHistory.cpp row. One deliberate behaviour change, stated in the PR description: a count above 256 that did not reach the plain slicer (257, a FINAL read, or a worker cluster above 256 replicas) is planned today, reading serially, and is now refused. Such a plan can still scatter or broadcast to that many exchange destinations, so distributed plans are affected; bounding the count bounds that fan-out, which is the memory cost this same ceiling already limits for the sibling settings. No result changes silently. This matches #109770, which refuses 257 for the sibling setting although the same fallback exists there.
i Invariants and contracts preserved? The check throws inside buildContext before its OptimizerContext is returned and published to the memo, so there is no optimizer state to unwind and no partially configured read; it is on the single-threaded planning path, so no lock or concurrency contract is touched. It is deliberately not placed inside sliceMarksAcrossBuckets: FINAL legitimately calls that with target_buckets * 16-derived counts and groups the resulting layers into at most 256 tasks afterwards, so a check there would drop non-intersecting ranges while intersecting ones remained. The FINAL positive control at 256 (correctly deduplicated result) pins that.

Suite check: the 65 cascades and distributed_plan stateless tests were run against this branch and against its base on the same explicit list. 19 fail on each arm, for the same two reasons on both (no parallel_replicas cluster and no stateless worker client in the minimal local test server). The sets differ by one test in each direction; both of those fail intermittently on both arms, neither enables the Cascades optimizer, and the new error message appears nowhere in either arm's log, so the bound cannot reach them. No regression.

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4fdbf54]

Summary: ✅


AI Review

Summary

This PR fixes the std::length_error reached from absurd Cascades node counts by rejecting cluster_node_count > 256 in buildContext, and the added stateless coverage exercises the original read-bucket failure paths. I found one blocker: the new guard turns a fan-out limit into a global cluster-size limit, so queries that the Cascades memo could still satisfy with an existing single-node plan now fail eagerly on any worker cluster above 256 nodes.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/Cascades/Optimizer.cpp:91] cluster_node_count is rejected before the optimizer knows whether the chosen plan will ever materialize a >256-way read or exchange fan-out. The root requirement still defaults to {1 node}, and the memo still keeps explicit single-node fallbacks (LocalReadImplementation, DefaultImplementation), so this change makes otherwise safe queries fail on a >256-replica worker cluster even when the winning plan would stay local. Please apply the cap where a multi-node plan is actually constructed, or otherwise preserve the existing single-node fallback for queries that do not need >256 fan-out.
Final Verdict

Changes requested.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 4/7 (57.14%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @KochetovNicolai, could you review this? The Cascades cluster node count is resolved in buildContext and checked only for zero, so a huge distributed_plan_workers_num reaches sliceMarksAcrossBuckets as a bucket count and it sizes a vector to that before the 256 ceiling is consulted, aborting debug and sanitizer builds; I bound the resolved count by the same ceiling, which also bounds the exchange fan-out sized from it.

"(also required for `distributed_plan_execute_locally` without a configured cluster).");
/// The count sizes the read buckets and the exchange fan-out, so the read-bucket ceiling bounds it
/// too: above it a plan would scatter to more destinations than a bucketed read may have.
if (context.cluster_node_count > ReadFromMergeTree::max_distributed_read_buckets)

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.

This turns the 256 fan-out cap into a global cluster-size cap. buildContext now throws before the optimizer has seen whether the winning plan will ever materialize a >256-way read or exchange, but the memo still has explicit {1 node} fallbacks (LocalReadImplementation, DefaultImplementation) and the root requirement still starts at {1 node}. On a worker cluster with more than 256 replicas, that means even queries whose chosen Cascades plan would stay local now fail up front. Can we move this bound to the places that actually construct >256 fan-out, or otherwise keep the existing single-node fallback for queries that do not need it?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and I reproduced it. This is a real over-refusal and the bound is in the wrong place.

Two A/B measurements on SELECT 1, with no table involved, so no fan-out can be constructed. Base is unpatched 071c010e (Build ID c26e0799), fix is this PR's head (Build ID ae0d046a):

node count from 256 257
distributed_plan_workers_num both answer 1 base answers 1, this PR raises Code: 471
a configured stateless_worker_client.cluster with that many <replica> entries, setting unset both answer 1 base answers 1, this PR raises Code: 471

The second row is your scenario exactly: an operator with a 257-node worker cluster sets nothing unusual, and SELECT 1 still fails up front.

I also checked whether anything above 256 is merely a dead configuration, and it is not. On a 300-replica cluster the read declines to bucket and falls back (No parallel read for 'default.t': the read splits into 0 buckets instead of 300), with no length_error, and execution proceeds past planning into TaskToHostMap::fillWorkerAddresses. Sweeping the count on base, 257, 1e5, 1e7, 1e9 and 2e9 all plan without aborting; the std::length_error I set out to fix only appears at the extreme tail (2^62 and 2^63-1, confirmed in the server log by Code: 1001 with sliceMarksAcrossBuckets and setupDistributedReadBuckets frames). So the guard refuses about 4.6e18 values of which only the far tail is dangerous, and 256 is roughly ten orders of magnitude below the real boundary.

One correction to my own PR description while I am here: it claims a count above the ceiling "cannot produce a bucketed read", implying nothing is lost. The fallback trace above shows what actually happens is a serial read that still runs, so the sentence understates the cost of the refusal.

On where the bound belongs, I would rather not pick unilaterally, because the options differ in which plans get produced:

  • clamp inside getCandidateNodeCounts (Cascades/RuleUtils.h:28), the single helper all four multi-node consumers go through (DistributionPassthrough.cpp:71, HashJoinImplementation.cpp:442, TopNImplementation.cpp:66, AggregationImplementations.cpp:227), so a large cluster plans at 256-way parallelism instead of failing;
  • bound only where fan-out is materialized, leaving the read path as is. It is already self-limiting: tryMakeBucketedReadVariant returns nullptr when actual_buckets != target_buckets (RuleUtils.cpp:39-41), which is what produced the fallback above;
  • keep a refusal but raise it only once a plan that actually needs the oversized fan-out is selected.

@davenger, you own this area: which of those shapes do you want? Clamping in getCandidateNodeCounts looks smallest to me and keeps large clusters working, but it changes planned parallelism on such clusters, so I would rather have your call than guess. I will rework the PR to whichever you prefer.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correcting myself on one point above: I wrote that the "cannot produce a bucketed read" sentence is in the PR description. It is not, it is in the commit message. The PR description already says the honest thing ("Such a plan reads serially but can still scatter to that many exchange destinations"), so the disclosure was there and I misattributed it. The substantive part stands: 257 through 2e9 plan fine on base, and the refusal costs a working serial read.

@PedroTadim PedroTadim assigned PedroTadim and unassigned PedroTadim Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4fdbf543a with master 071c010ef (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 701.99 MiB 698.96 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov 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.

LGTM

@davenger
davenger added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit ff4ddd3 Aug 21, 2026
353 of 356 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

5 participants