Skip to content

Rule based tasks and threads sizing in distributed plan - #126945

Merged
shankar-iyer merged 7 commits into
ClickHouse:masterfrom
shankar-iyer:size_distributed_plan_readers
Oct 28, 2026
Merged

shankar-iyer merged 7 commits into
ClickHouse:masterfrom
shankar-iyer:size_distributed_plan_readers

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

With make_distributed_plan and the rule-based planner, every distributed read was split into a fixed distributed_plan_default_reader_bucket_count (8) tasks, whatever the data size or the number of workers: with 50 workers only 8 read, and a small read still paid for 8 tasks. When the read and the following "any" scatter had different bucket counts, an extra exchange of raw rows also stayed in the plan. Workers also used the initiator's max_threads, which reflects the initiator's cores, not theirs.

  • distributed_plan_default_reader_bucket_count now defaults to 0: one read task per distributed_plan_min_rows_per_reader (new, default 1000000) selected rows, at least one and at most the number of workers. An explicit value still wins.
  • Keyless scatters (partial aggregation, distributed sorting, the left side of a broadcast join) take the bucket count of the distributed input below them, so optimizeExchanges removes them and the step runs inside the read tasks. Keyed shuffles still use distributed_plan_default_shuffle_join_bucket_count.
  • A stateless worker caps the received max_threads at its own number of CPU cores.

The cost-based optimizer (enable_cascades_optimizer) is not affected. Existing tests that assert on plan shape or count per-task runtime filter states were updated or pinned to 8 readers; query results are unchanged.

Changelog category (leave one):

  • Improvement

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

The rule-based distributed query plan (make_distributed_plan) now chooses the number of read tasks from the rows to read and the number of workers (distributed_plan_default_reader_bucket_count = 0 by default, sized by the new setting distributed_plan_min_rows_per_reader), removes the exchange between a read and a partial aggregation or sort, and caps max_threads on stateless workers at their number of CPU cores.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.840-master (included in 26.11 and later)

`distributed_plan_default_reader_bucket_count` now defaults to `0`, which
chooses the number of read tasks automatically: one task per
`distributed_plan_min_rows_per_reader` (new setting, default 1000000) rows
selected by the read, at least one, and at most the number of workers. An
explicit value still overrides it.

Keyless scatters (partial aggregation, distributed sorting, the left side of a
broadcast join) take the bucket count of the distributed input below them, so
`optimizeExchanges` removes the exchange and the step runs in the tasks that
produce its input.

A stateless worker caps the `max_threads` it receives from the initiator at its
own number of CPU cores.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [de5a3df]

Summary: ✅


AI Review

Summary

This PR sizes rule-based distributed reads from selected rows and worker count, fuses keyless exchanges into upstream tasks, and adjusts worker thread budgets. Request changes: two worker-thread contracts remain broken, including one previously reported issue that is still present.

Findings

⚠️ Majors

  • src/QueryPipeline/DistributedPlanExecutor.cpp:1148: An explicit numeric thread cap can be discarded. With a profile containing max_threads = 0, converting the profile value to SettingFieldMaxThreads resolves it to the initiator's core count. An explicit numeric override equal to that count compares equal and is removed. An 8-thread cap on an 8-core initiator can therefore become 64 threads per task on a larger worker. Preserve a numeric override when the profile value is automatic by comparing is_auto as well as the number.
  • src/QueryPipeline/DistributedPlanExecutor.cpp:1152: Replica reads retain the initiator's machine-derived parallelism. Removing max_threads from task settings leaves ReadFromMergeTree's serialized stream count unchanged: serialize writes getNumStreams, deserialize forwards it to readFromParts, and pipeline construction uses requested_num_streams. A small initiator therefore still limits read streams and expressions before aggregation on a larger worker. Resolve machine-derived read parallelism from the worker's budget while preserving explicitly serial reads and user caps. This remains open in the existing review thread; no duplicate inline comment was posted.
Tests
  • ⚠️ Extend 05443_distributed_plan_worker_max_threads_from_profile with an automatic profile and an explicit numeric override equal to the initiator's automatic value; assert that the numeric cap reaches the worker.
  • ⚠️ Add focused evidence of actual worker read/expression parallelism with a smaller initiator budget and enough marks to parallelize. The current test checks only Settings['max_threads'], which cannot detect the serialized read-stream limit.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so runtime tests were not rerun. The Cloud-only worker-read implementation is absent from this checkout; its runtime behavior needs Cloud test evidence.
Final Verdict

Status: ⚠️ Request changes. Preserve explicit numeric caps over automatic profile values, resolve replica-read parallelism from the worker budget, and add the focused regression coverage above.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 20, 2026
@davenger davenger self-assigned this Oct 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit de5a3df1a7876589f27157f2f49682bd30993260 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

shankar-iyer and others added 3 commits October 21, 2026 11:59
… plan

The automatic read bucket count resolved the worker provider while building
`QueryPlanOptimizationSettings`. With `distributed_plan_execute_locally = 1` and
`distributed_plan_workers_num = 0`, a configuration without a default worker
cluster then threw `NO_ELEMENTS_IN_CONFIG`, even though the plan runs
in-process, and it did so before `applyDistributedPlanFallbackToLocal` could
decline distribution.

Local execution now caps the count by `distributed_plan_workers_num` (`0` means
no cap) without touching the provider. Otherwise the worker count is resolved
lazily, only when `tryMakeDistributedRead` sizes a distributed read.

ClickHouse#126945 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…an_readers

Resolve the conflict with the `ShufflePartialStates` aggregation strategy: the "any" scatter
under a partial aggregation and its gather take the bucket count of the distributed input below
them in both partial-aggregation strategies, so the exchange is removed. Update the reference of
`04878_distributed_plan_shuffle_bucket_order_promise`, where that exchange is now gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tter bucket count

The scatter under a distributed sorting now takes the bucket count of the distributed read below
it, so different reader and shuffle bucket counts no longer leave a redistribution between the
ordered read and the sorting. Replace the test with
`test_read_in_order_with_reader_buckets_unlike_scatter`, which checks that the pair collapses
with those settings and that the ordered read still returns the right rows.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126945&sha=2a766ed8c7494a5b55bfab361c3b5396c90be395&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%20targeted%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
shankar-iyer and others added 2 commits October 22, 2026 05:08
The initiator sent its `max_threads` to every worker task, so a small initiator held large workers
to its own thread count: with `max_threads` from the settings profile (or explicitly `auto`, which
is sent as the initiator's core count), a 64-core worker ran each task with the initiator's 16.

The initiator now drops `max_threads` from the settings it sends when it is `auto` or equals the
value of the user's settings profile, so the worker uses its own. A value the user sets over the
profile is still sent, and the worker caps it at its number of CPU cores.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
}

if (!user_capped_max_threads)
std::erase_if(changes, [](const SettingChange & change) { return change.name == "max_threads"; });

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.

[P2] Recompute read parallelism when dropping the initiator's thread limit

Removing max_threads from the settings does not remove the initiator's parallelism from the serialized read. On the replica read path, ReadFromMergeTree::serialize writes getNumStreams, deserialize passes that value unchanged to readFromParts, and initializePipeline creates the readers from requested_num_streams, rather than the worker's BuildQueryPipelineSettings::max_threads.

For example, with the default stream ratio, an initiator profile of max_threads = 3 still produces at most three read streams per task on a 64-core worker, even for a large unordered read with enough marks. Expressions and partial aggregation fused into those read tasks consequently keep that smaller input parallelism. This leaves the small-initiator bottleneck that this change is intended to remove, despite the worker's settings log showing that max_threads was omitted. This path is used in OSS and with distributed_plan_prefer_replicas_over_workers.

Please resolve machine-derived read parallelism from the worker's budget when reconstructing the fragment, while preserving deliberately serial reads and explicit user caps. Extend the focused test to inspect worker read/transform parallelism; checking only Settings['max_threads'] cannot catch this.

{
for (const auto & change : context->getAccess()->getDefaultSettings())
if (change.name == "max_threads")
user_capped_max_threads = SettingFieldMaxThreads(change.value).value != max_threads.value;

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.

[P2] Preserve numeric caps that override an automatic profile value

With a settings profile containing max_threads = 0, SettingFieldMaxThreads(change.value) resolves the profile's automatic value to the initiator's core count. If the query explicitly sets max_threads to that same number, this comparison clears user_capped_max_threads even though the query's value is numeric (is_auto == false). The explicit cap is then erased from the task settings. For example, an explicit cap of 8 on an 8-core initiator becomes the worker's default of 64 on a 64-core worker, allowing exchange/aggregation stages to exceed the requested limit.

Preserve the cap when the profile value is automatic; compare is_auto as well as the resolved number. Extend the profile test with an automatic profile and an explicit numeric override equal to the initiator's automatic value, checking that workers receive the numeric cap.

@shankar-iyer
shankar-iyer added this pull request to the merge queue Oct 28, 2026
Merged via the queue into ClickHouse:master with commit 0525e0c Oct 28, 2026
178 checks passed
@shankar-iyer
shankar-iyer deleted the size_distributed_plan_readers branch October 28, 2026 05:56
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 28, 2026
@clickhouse-gh clickhouse-gh Bot added comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... pr-improvement Pull request with some product improvements 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.

3 participants