Skip to content

Shuffle partial aggregation states instead of input rows in distributed aggregation - #123537

Merged
davenger merged 13 commits into
masterfrom
distributed-aggregation-shuffle-partial-states
Oct 21, 2026
Merged

davenger merged 13 commits into
masterfrom
distributed-aggregation-shuffle-partial-states

Conversation

@davenger

@davenger davenger commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

With make_distributed_plan, the rule-based planner distributes a GROUP BY with many groups by shuffling every input row by the group keys and aggregating each bucket after the shuffle. Nothing reduces the rows before the exchange, so a query that sees each key many times on each reader serializes, sends and deserializes all of its input. The Cascades optimizer can aggregate before the exchange, but it can only gather the partial states to one node and merge them there, which becomes the bottleneck when there are many groups.

This PR adds the plan shape that partially aggregates where the data is read, shuffles the partial states by the group keys and merges them per bucket:

GatherExchange
  MergingAggregated (merge)
    ShuffleExchange (by hash(keys))
      Aggregating (partial)
        ReadFromMergeTree
  • Rule-based planner: a new strategy replaces the shuffle of input rows. The shuffle of input rows stays when column statistics show fewer than two input rows per group, because partial aggregation would then cost a hash table pass without reducing the data.
  • Cascades: a new implementation rule for the merge half of a two-stage aggregation offers a merge per bucket over a shuffle by the keys, next to the merge on one node; the cost model chooses.
  • Cascades estimator: a read records NDV 0 for a column without statistics, and the group-count estimate took it as known, which estimated a single group for any input and made a merge of all groups on one node look free. NDV 0 now falls back to the default ratio.
  • ScatterByPartitionTransform keeps AggregatedChunkInfo on each part of a split chunk, which the merge on the other side needs.
  • The new setting distributed_plan_partial_aggregation_before_shuffle (default true) turns the new shape off for both planners.

A GROUP BY where almost every row is a separate group and the planner has no statistics now does an extra hash table pass on the readers. A run-time bypass of partial aggregation that does not reduce the data is planned as a follow-up.

Changelog category (leave one):

  • Experimental Feature

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

A distributed query plan (make_distributed_plan) aggregates partially before it shuffles a GROUP BY by its keys, and merges the partial states per bucket, instead of shuffling every input row. Controlled by the new setting distributed_plan_partial_aggregation_before_shuffle.

🤖 Generated with Claude Code


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

Version info

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

davenger and others added 2 commits October 1, 2026 18:31
…tion-shuffle-partial-states

# Conflicts:
#	src/Core/Settings.cpp
#	src/Core/SettingsChangesHistory.cpp
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23984ab]

Summary: ✅


AI Review

Summary

The PR adds partial aggregation before a shuffle and per-bucket merging to both distributed planners. Request changes: differing reader/shuffle bucket counts introduce an extra exchange of the entire raw input, and the previously reported loss of spilling remains in the current code.

Findings

⚠️ Majors

  • makeDistributed.cpp:922: Partial aggregation must precede redistribution of raw rows. The helper places the partial aggregation on the destination shuffle buckets. When reader and shuffle counts differ, its any scatter survives exchange optimization, so every raw row is shuffled before aggregation and the states are shuffled again afterwards. The updated 04878_distributed_plan_shuffle_bucket_order_promise.reference:83-90 shows both exchanges; the previous plan has only the keyed shuffle. Keep the partial aggregation on the source buckets and send its states through one keyed shuffle to the merge buckets.

  • makeDistributed.cpp:937, AggregationImplementations.cpp:488: External aggregation no longer bounds the receiver's state memory. Both strategies select MergingAggregatedTransform, whose consume retains every incoming state chunk until input finishes; neither that accumulation nor Aggregator::mergeBlocks spills according to max_bytes_before_external_group_by. Overlapping keys or large states can therefore raise MEMORY_LIMIT_EXCEEDED where the previous row-shuffle aggregation spills and succeeds. The existing thread records that difference with four readers, 2,000,000 rows, 100,000 wide keys, a 2,000,000-byte spill threshold, and a 120,000,000-byte memory limit. Use an incremental merge that can spill, or retain a strategy that honors external aggregation for this case.
    [dismissed by author -- https://github.com/Shuffle partial aggregation states instead of input rows in distributed aggregation #123537#discussion_r4264814998] A maintainer deferred spilling to a follow-up; the current receiver still buffers all states without spilling, so the memory-limit regression remains.

Missing context / blind spots
  • ⚠️ No local ClickHouse executable/build was available, so SQL reproducers were not rerun. The findings follow the current code, committed plan output, and the prior recorded spilling reproducer; executing the focused cases on the current head would close the runtime-validation gap.
Tests
  • ⚠️ Pin different reader and shuffle counts, such as 8 and 2, and assert that only the keyed state shuffle remains while results match local execution.
  • ⚠️ Add finite-memory external-aggregation coverage for both planners with overlapping keys or large aggregate states; small in-memory result fingerprints do not exercise the receiver's spilling behavior.
Final Verdict

⚠️ Request changes. Keep partial aggregation on the source buckets, preserve external aggregation at the shuffled receiver, and add the focused coverage above. The spilling concern remains summary-only in recognition of the existing follow-up decision.

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 2, 2026
davenger and others added 2 commits October 2, 2026 17:38
…rows in the rule-based planner

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tion-shuffle-partial-states

# Conflicts:
#	tests/queries/0_stateless/04926_cascades_aggregation_pushdown.reference
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

@shankar-iyer shankar-iyer self-assigned this Oct 5, 2026
…tion-shuffle-partial-states

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// which the memory-efficient merge cannot consume.
auto & merge_node = nodes.emplace_back();
merge_node.step = makeMergeOfPartialStates(
*aggregating_step, exchange_scatter_node.step->getOutputHeader(), /*memory_efficient_merge=*/false,

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.

⚠️ Major — Preserve spilling at the shuffled merge

Passing memory_efficient_merge = false selects MergingAggregatedTransform, which retains all incoming state chunks in bucket_to_chunks until input finishes. Neither that accumulation nor Aggregator::mergeBlocks spills according to max_bytes_before_external_group_by. The old row-shuffle path uses AggregatingTransform, which combines and spills while receiving. Consequently, overlapping keys from several readers can accumulate multiple copies of the same keys/states at a skewed receiver and exceed max_memory_usage, even though the previous plan completes with external aggregation enabled. The Cascades alternative has the same issue through cloneWithoutMemoryEfficientAggregation.

I reproduced this with the CI binary for 83b074ec52e8f428ac6a560a349f0b1db154e228: four reader/shuffle tasks, Streaming exchanges, and 2,000,000 rows containing 100,000 distinct 264-byte String keys repeated across readers and routed to one shuffle partition. For this query:

SELECT count(), sum(c)
FROM (SELECT k, count() AS c FROM t_skew GROUP BY k)
SETTINGS max_bytes_before_external_group_by = 2000000,
         max_bytes_ratio_before_external_group_by = 0,
         max_memory_usage = 120000000;

With distributed_plan_partial_aggregation_before_shuffle = 0, it returns 100000, 2000000 and the aggregation receiver writes 58 spill files. With the setting enabled, the partial tasks spill too, but the merge receiver throws MEMORY_LIMIT_EXCEEDED while deserializing the accumulated states (StreamingExchangeDeserializingTransform → SerializationAggregateFunction::deserializeBinaryBulk → Arena::addMemoryChunk).

Please use a merge that can combine/spill unordered input incrementally, or retain a plan that honors external aggregation when this merge cannot, and add focused memory-limit coverage for both planners.

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.

Spilling can be handled in follow on PR.

@davenger
davenger force-pushed the distributed-aggregation-shuffle-partial-states branch from 554634a to 83b074e Compare October 14, 2026 19:21
Comment thread src/Core/Settings.cpp

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.

BETA or EXPERIMENTAL

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 19, 2026
Comment thread src/Core/Settings.cpp Resolved
@davenger
davenger enabled auto-merge October 19, 2026 15:25
@davenger
davenger added this pull request to the merge queue Oct 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 19, 2026
…tion-shuffle-partial-states

# Conflicts:
#	tests/queries/0_stateless/03394_distributed_shuffle_join_with_aggregation.reference
#	tests/queries/0_stateless/03394_distributed_shuffle_join_with_in.reference
@davenger
davenger enabled auto-merge October 20, 2026 12:59
@davenger
davenger added this pull request to the merge queue Oct 20, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 20, 2026
davenger and others added 2 commits October 20, 2026 16:13
…tion-shuffle-partial-states

# Conflicts:
#	tests/queries/0_stateless/05218_distributed_plan_exchange_compression_codec.sql
/// ShuffleExchange (by hash(keys))
/// Aggregating (partial)
/// <source>
auto & partial_aggregation_node = addPartialAggregation(*aggregating_step, source, nodes, bucket_count, /*produce_results_in_bucket_order=*/false);

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.

⚠️ Major — Keep partial aggregation on the reader buckets

This passes the destination shuffle count to addPartialAggregation, so its any scatter redistributes the raw input before aggregating whenever the reader and shuffle counts differ. optimizeExchanges only removes that scatter/shuffle when the counts match. For example, with distributed_plan_default_reader_bucket_count = 8 and distributed_plan_default_shuffle_join_bucket_count = 2, the new plan has a raw-row ShuffleExchange (any) below the partial aggregation and a second keyed shuffle above it. The updated 04878_distributed_plan_shuffle_bucket_order_promise.reference:83-90 already shows this shape.

The previous plan needed only the keyed raw-row shuffle. The new plan still transfers every input row, then additionally transfers the states and performs another aggregation pass, defeating the promised reduction before the exchange for these supported settings.

Keep the partial aggregation at the source bucket count and use a single reader-to-merge shuffle for its states. Please cover unequal reader/shuffle counts with a plan assertion that no raw-row exchange remains below the partial aggregation.

@davenger
davenger enabled auto-merge October 21, 2026 07:41
@davenger
davenger added this pull request to the merge queue Oct 21, 2026
Merged via the queue into master with commit f7de1ab Oct 21, 2026
179 checks passed
@davenger
davenger deleted the distributed-aggregation-shuffle-partial-states branch October 21, 2026 10:49
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 21, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 21, 2026
…ault

The test checks that the streaming exchange compresses, i.e. that it writes
fewer bytes to the sockets than the Native blocks it serializes. Since ClickHouse#123537
a distributed aggregation without NDV statistics shuffles partial aggregation
states. With a randomized `group_by_two_level_threshold = 1` or
`group_by_two_level_threshold_bytes = 1` the partial aggregation is two-level,
so the states cross the exchange as ~1000 packets of ~110 bytes, and the
per-packet framing, written for every codec, outweighs what the codec saves:
LZ4 sends 133 KB for 112 KB serialized (NONE sends 156 KB).

Force the shuffle of the input rows, as 478d701 did for the sibling
05218: the exchange then carries ~4 MB in 14 packets whatever the aggregation
settings, and LZ4 sends 11% of it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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-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.

3 participants