Skip to content

Cap distributed-plan bucket counts in the reader/join optimization pass - #109770

Merged
davenger merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-makedistributedplan-length-error
Jul 8, 2026
Merged

davenger merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-makedistributedplan-length-error

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a LOGICAL_ERROR (std::length_error) when a query with the experimental setting make_distributed_plan = 1 used a very large distributed_plan_default_reader_bucket_count or distributed_plan_default_shuffle_join_bucket_count. Such values are now rejected with INVALID_SETTING_VALUE.

Description

The distributed-plan bucket-count cap (validateBucketCount, max 256) was applied only inside makeDistributedPlan. But the tryMakeDistributedRead / tryMakeDistributedJoin / tryMakeDistributedAggregation / tryMakeDistributedSorting pass in optimizeTreeSecondPass runs earlier and reads the raw setting value directly.

For the reader path, tryMakeDistributedRead passes distributed_plan_default_reader_bucket_count into ReadFromMergeTree::setupDistributedReadBuckets, which calls sliceMarksAcrossBuckets(parts, bucket_count) -> std::vector<RangesInDataPartsDescription> result(bucket_count). A huge bucket count throws std::length_error (release builds throw, debug/sanitizer builds abort) before the max_total_buckets = 256 check is ever reached.

SELECT sumOrNull(x) FROM t
SETTINGS make_distributed_plan = 1, distributed_plan_default_reader_bucket_count = 9223372036854775807;

Fix: hoist the validation into validateDistributedPlanBucketCounts and call it from the single up-front distributed-plan gate in optimizeTreeSecondPass, so both entry points (the tryMakeDistributed* pass and makeDistributedPlan) and both bucket-count settings are covered.

Found by the AST fuzzer (AST fuzzer (amd_debug, targeted)) on several PR runs, e.g. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106135&sha=61d98ee87c9d67bf7481342dce69879d5d77141b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 with Logical error: 'std::exception. Code: 1001, type: std::length_error, e.what() = vector' in sliceMarksAcrossBuckets / ReadFromMergeTree::setupDistributedReadBuckets / tryMakeDistributedRead.

Related: earlier cap for the makeDistributedPlan entry point in commit 340e648 ("Cap distributed plan bucket counts to limit memory consumption").

Version info

  • Merged into: 26.7.1.691 (included in 26.7 and later)

The distributed-plan bucket-count cap (validateBucketCount, max 256) was applied
only in makeDistributedPlan. The tryMakeDistributedRead/Join/Aggregation/Sorting
pass in optimizeTreeSecondPass runs earlier and used the raw setting value, so a
huge distributed_plan_default_reader_bucket_count sized a
std::vector<RangesInDataPartsDescription> to that value in sliceMarksAcrossBuckets
and threw std::length_error (LOGICAL_ERROR abort in debug/sanitizer builds) before
the max-buckets check. Hoist the validation to the single up-front distributed-plan
gate so both entry points and both bucket-count settings are covered.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local (debug): SELECT sumOrNull(x) FROM t SETTINGS make_distributed_plan=1, distributed_plan_execute_locally=1, distributed_plan_max_rows_to_broadcast=0, distributed_plan_default_reader_bucket_count=9223372036854775807 aborts (SIGABRT, exit 134) every time.
b Root cause explained? tryMakeDistributedRead (in optimizeTreeSecondPass, which runs before makeDistributedPlan) passes the raw distributed_plan_default_reader_bucket_count into setupDistributedReadBuckets -> sliceMarksAcrossBuckets -> std::vector<RangesInDataPartsDescription> result(bucket_count). A huge value throws std::length_error before the max_total_buckets=256 check. The existing validateBucketCount cap only guarded makeDistributedPlan, not this earlier pass.
c Fix matches root cause? Yes. The validation is hoisted to the single up-front distributed-plan gate in optimizeTreeSecondPass, so it runs before the tryMakeDistributed* pass reads the settings. No band-aid (no widened bound, no defensive size clamp).
d Test intent preserved / new tests added? New test 04509_distributed_plan_bucket_count_cap added: both settings at INT64_MAX must throw INVALID_SETTING_VALUE (reader and shuffle-join paths); a value at the cap (256) still builds the plan.
e Both directions demonstrated? Yes. Without fix: SIGABRT with length_error in sliceMarksAcrossBuckets/setupDistributedReadBuckets/tryMakeDistributedRead. With fix: clean Code: 471 INVALID_SETTING_VALUE (both settings), cap=256 returns 1. Verified on a real server (Build ID matched).
f Fix is general across code paths? Yes. Both distributed-plan entry points (optimizeTreeSecondPass's tryMakeDistributed* pass and makeDistributedPlan) now share one validator, and it covers both bucket-count settings (reader and shuffle_join).
g Fix generalizes across inputs? The guard is a numeric range check on the two settings; any value > 256 is rejected identically regardless of query shape / datatypes. Verified for the reader (aggregation) and shuffle-join paths; the boundary value 256 is accepted.
h Backward compatible? (maintainer-approved exception only) Yes, no exception needed. The 256 cap already exists (commit 340e648); this only closes an unguarded entry point. make_distributed_plan is an experimental, default-off feature. No setting default changed, no format change.
i Invariants and contracts preserved? Yes. validateDistributedPlanBucketCounts throws before any bucket count is used to size a vector or exchange fan-out, upholding setupDistributedReadBuckets/sliceMarksAcrossBuckets's implicit precondition that bucket_count <= MAX_DISTRIBUTED_PLAN_BUCKET_COUNT. No behavior change for in-range values.

Session id: cron:clickhouse-worker-slot-0:20260708-130900

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @davenger @KochetovNicolai — could you review this? It fixes a std::length_error abort in the experimental make_distributed_plan path: the bucket-count cap was only enforced in makeDistributedPlan, so tryMakeDistributedRead in the earlier optimizeTreeSecondPass pass sized a vector to a raw huge distributed_plan_default_reader_bucket_count before the max-buckets check. The validation is hoisted to the up-front distributed-plan gate so both entry points and both bucket-count settings are covered.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6fc6679]

Summary: ✅


AI Review

Summary

This PR hoists distributed-plan bucket-count validation into optimizeTreeSecondPass so the tryMakeDistributed* pass rejects oversized distributed_plan_default_reader_bucket_count / distributed_plan_default_shuffle_join_bucket_count values before any read-bucket vector or exchange fan-out is sized from them, while keeping the existing guard in makeDistributedPlan for direct callers. The updated 04320_distributed_plan_read_rejects.sql coverage exercises the near-maximum regression cases in a test that already pins max_rows_to_group_by = 0 and no-old-analyzer, and I did not find any remaining correctness or evidence gaps in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
Comment on lines +2 to +10
-- no-fasttest: make_distributed_plan is an experimental feature

-- An out-of-range distributed-plan bucket count must be rejected with INVALID_SETTING_VALUE, not size a
-- vector to the raw value and abort (std::length_error) while building the plan. The reader path
-- (tryMakeDistributedRead) is validated in optimizeTreeSecondPass, the shuffle-join path in makeDistributedPlan.

DROP TABLE IF EXISTS t_bucket_cap;
CREATE TABLE t_bucket_cap (x UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_bucket_cap SELECT number FROM numbers(200000);

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.

@groeneai this test is too heavy for a a simple fix. Do not add a table with many rows just to test this setting. Is there an existing test that checks for max bucket count but misses these cases? It it already exists, add more cases there

Comment on lines +59 to +61
/// Validate both bucket-count settings up front, before any distributed optimization reads them to size
/// exchange fan-outs or read-bucket vectors. Reachable from optimizeTreeSecondPass's tryMakeDistributed*
/// pass (which uses the raw values directly) as well as makeDistributedPlan.

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.

@groeneai This comment explains trivial things, but bloats the code. Remove it

@davenger davenger self-assigned this Jul 8, 2026
… and trivial comment

Per review on ClickHouse#109770: move the bucket-count cap coverage into the existing
04320_distributed_plan_read_rejects test (which already pins max_rows_to_group_by=0
and carries no-old-analyzer) instead of a new heavy table-backed test, and add the
near-type-maximum cases that exercise the tryMakeDistributedRead pass validation.
Remove the trivial explanatory comment in makeDistributed.cpp.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

@davenger done in 6fc6679:

  • Dropped the new 04509 test. Moved the coverage into the existing 04320_distributed_plan_read_rejects.sql, which already checks a 257 (just over the 256 cap) bucket count for both settings. Added two near-type-maximum cases (9223372036854775807), which are the ones the earlier tryMakeDistributedRead pass previously sized a vector from and aborted on (std::length_error); 257 alone was caught later by the makeDistributedPlan check even without this fix. That test already pins max_rows_to_group_by = 0 and carries no-old-analyzer, so both bot points are covered by construction; no data table added.
  • Removed the trivial comment at makeDistributed.cpp:61.
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. SELECT sum(x) ... SETTINGS make_distributed_plan=1, distributed_plan_default_reader_bucket_count=9223372036854775807 aborted with std::length_error before the fix; now returns INVALID_SETTING_VALUE.
b Root cause explained? The bucket-count cap ran only in makeDistributedPlan. The earlier tryMakeDistributedRead pass in optimizeTreeSecondPass used the raw value to size a std::vector<RangesInDataPartsDescription>, throwing std::length_error before any cap check.
c Fix matches root cause? Yes. Validation is hoisted to the single up-front distributed-plan gate in optimizeTreeSecondPass, covering both entry points and both settings.
d Test intent preserved / new cases added? Extended the existing cap test with the near-max cases the reader-pass fix targets; no assertion weakened.
e Both directions? Fails (abort) without the gate, passes (INVALID_SETTING_VALUE) with it. Confirmed all four cap cases return code 471 on the built binary.
f General, not narrow? Both settings and both entry points validated by the shared validateDistributedPlanBucketCounts.
g Generalizes across inputs? Covered: 257 (just over cap) and near-type-max for shuffle and reader settings.
h Backward compatible? N/A: rejects a value that previously aborted; no valid behavior changes.
i Invariants preserved? Validation runs before any pass reads the values to size vectors/fan-outs.

Session id: cron:clickhouse-worker-slot-5:20260708-141700

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6fc6679

Every failure below has an owner: a fixing PR (ours), plus the exempt private sync. Both AST fuzzer findings are chronic trunk fuzzer STIDs (not caused by this distributed-plan bucket-cap fix), each already owned by an open fixing PR of ours.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Inconsistent AST formatting (STID 1941-26fa) chronic trunk fuzzer finding (96 PRs / 30d) #109176 (ours, open)
AST fuzzer (amd_debug, targeted) / Block structure mismatch (STID 0993-27f0) chronic trunk fuzzer finding (166 PRs / 30d) #107719 (ours, open)
Mergeable Check / PR aggregator of the above same
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260708-183000

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.90% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code

Full report · Diff report

@davenger
davenger added this pull request to the merge queue Jul 8, 2026
Merged via the queue into ClickHouse:master with commit 73d7466 Jul 8, 2026
342 of 345 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 8, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… and trivial comment

Per review on ClickHouse#109770: move the bucket-count cap coverage into the existing
04320_distributed_plan_read_rejects test (which already pins max_rows_to_group_by=0
and carries no-old-analyzer) instead of a new heavy table-backed test, and add the
near-type-maximum cases that exercise the tryMakeDistributedRead pass validation.
Remove the trivial explanatory comment in makeDistributed.cpp.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…dplan-length-error

Cap distributed-plan bucket counts in the reader/join optimization pass
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 pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants