Skip to content

Fix wrong results of the partial aggregation strategy in distributed query plans - #114523

Merged
nickitat merged 12 commits into
masterfrom
fix_distributed_plan_aggregation_bucket_order
Aug 21, 2026
Merged

nickitat merged 12 commits into
masterfrom
fix_distributed_plan_aggregation_bucket_order

Conversation

@davenger

@davenger davenger commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

The partial+merge aggregation strategy of make_distributed_plan rewrites a final aggregation into a partial AggregatingStep plus a memory-efficient MergingAggregatedStep. The memory-efficient merge consumes each input as a stream of two-level buckets in ascending order, but the rewrite kept should_produce_results_in_order_of_bucket_number = false on the partial step, so its multi-stream output was combined into the single exchange stream in arbitrary order. When a bucket arrived after the merge had already emitted it, the merge emitted it a second time: duplicated GROUP BY keys with split aggregate states (for ClickBench Q08, a wrong COUNT(DISTINCT UserID)).

The fix, one commit each:

  • Make the row count estimation look through LogicalExchangeStep. The #if CLICKHOUSE_CLOUD guard around it was needed when the exchange steps existed only in the private repo; since they are in the public repo, the guard only made every aggregation over a distributed read fall back to the Shuffle strategy in non-cloud builds (and masked this bug there).
  • Validate the bucket delivery order in GroupingAggregatedTransform: an unannounced late bucket now fails with a LOGICAL_ERROR exception instead of silently duplicating groups.
  • Wait for delayed buckets in GroupingAggregatedTransform when the consumer needs the output in bucket order, and release the announcements of finished inputs. Covered by a gtest.
  • Build the partial step with should_produce_results_in_order_of_bucket_number = true when the merge is memory-efficient (AggregatingStep::cloneAsPartial). The partial aggregation then produces a single bucket-ordered stream per worker, the same contract the classic distributed path establishes on shards. Covered by a stateless test that reproduces the duplicated keys on the code without the fix (about 80% of single runs, 8 repetitions, 50k rows, ~0.5s).

Changelog category (leave one):

  • Experimental Feature

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

Fix duplicated GROUP BY keys in the partial aggregation strategy of make_distributed_plan, and allow this strategy for aggregations over a distributed read.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.8.1.1855 (included in 26.8 and later)
  • Backported to: 26.7.8.11, 26.6.6.14

davenger and others added 4 commits August 12, 2026 17:36
…nnounced late bucket now fails with an exception instead of duplicating groups

Co-Authored-By: Claude Fable 5 <[email protected]>
…nsumer needs them in order

Co-Authored-By: Claude Fable 5 <[email protected]>
…d plan merges it memory-efficiently

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b8a88ec]

Summary: ✅


AI Review

Summary

This PR fixes wrong results in the distributed and parallel partial-aggregation path by forcing bucket-ordered partial outputs when the memory-efficient merge path is used, and by turning duplicate bucket delivery into a LOGICAL_ERROR exception instead of silently returning duplicated groups. On the current head I did not find any remaining correctness, safety, or PR-metadata issues in the diff; the earlier bucket-order contract gaps in makeDistributed and applyParallelReplicas are addressed.

Missing context / blind spots
  • ⚠️ The only CI artifact available during this review was the build-profile-diff report, so I could not cross-check the new query coverage against functional CI logs.
Final Verdict

✅ No new findings on the current head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 91.90% 92.00% +0.10%
Branches 79.30% 79.30% +0.00%

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

Full report · Diff report

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

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b8a88ecae with master 64f260330 (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 702.08 MiB 699.05 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

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

Job report

@nickitat nickitat self-assigned this Aug 13, 2026
@nickitat

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

Copilot AI commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Resolved in commit 2626bb37336 by merging master into this branch and fixing conflicts in src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.h and src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.cpp.

@CLAassistant

CLAassistant commented Aug 17, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Copilot AI requested a review from nickitat August 17, 2026 20:30

QueryPlanStepPtr AggregatingStep::cloneAsPartial(bool produce_results_in_order_of_bucket_number) const
{
return std::make_unique<AggregatingStep>(

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.

Maybe reuse the clone + setFinal(false) pattern. It tells much clearer how the new step is different from the source one.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok

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.

I don't think we need these changes in GroupingAggregatedTransform. Everything should work the same way it works in normal distributed queries and with parallel replicas. I.e., the fix we got from merge with master should be enough.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed them. One question: the Bucket {} is pushed twice check in pushData is a chassert, so a release build silently returns the duplicated groups (the expression is not evaluated there, so pushed_buckets stays empty). What do you think about converting it to a LOGICAL_ERROR exception, so that this failure mode cannot go unnoticed in release builds? It fires only on an actual duplicate emission, so the unannounced out-of-order streams from MergingAggregatedTransform which buffer correctly are not affected. The cost is one set insert per pushed bucket.

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.

What do you think about converting it to a LOGICAL_ERROR exception, so that this failure mode cannot go unnoticed in release builds?

No objections

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done

@davenger
davenger force-pushed the fix_distributed_plan_aggregation_bucket_order branch from 6e9fe29 to cdf63c6 Compare August 19, 2026 13:08
@PedroTadim

Copy link
Copy Markdown
Member

Public 26.6 and 26.7 branches are still missing the fix and hit an assertion error fixed by this PR https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=118728&sha=latest&name_0=BackportPR Backporting to those

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 8, 2026
nickitat added a commit that referenced this pull request Sep 8, 2026
Cherry pick #114523 to 26.7: Fix wrong results of the partial aggregation strategy in distributed query plans
robot-clickhouse added a commit that referenced this pull request Sep 8, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Sep 8, 2026
Cherry pick #114523 to 26.6: Fix wrong results of the partial aggregation strategy in distributed query plans
robot-clickhouse added a commit that referenced this pull request Sep 8, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 8, 2026
PedroTadim added a commit that referenced this pull request Sep 10, 2026
…ettings

  applyParallelReplicas.cpp:85:55: error: use of undeclared identifier 'optimization_settings'

On master `ApplyParallelReplicasVisitor` holds a `QueryPlanOptimizationSettings`
reference; on 26.7 it does not, and `applyParallelReplicas` ignores its settings
argument. The memory-efficient merge is correspondingly hard-coded to `false`
there, so the cherry-pick only had to move that constant up, not master's
expression. #114523's real fix for this branch is in `makeDistributed.cpp`,
which does have the settings in scope and is unchanged from the original.

Co-Authored-By: Claude Opus 5 (1M context) <[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.
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #114523 to 26.7: Fix wrong results of the partial aggregation strategy in distributed query plans
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #114523 to 26.6: Fix wrong results of the partial aggregation strategy in distributed query plans
@blau-ai blau-ai mentioned this pull request Oct 8, 2026
20 of 30 tasks
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 3, 2026
…nless no consumer needs stream order

With `parallel_replicas_mode = 'sampling_key'` on any cluster, or a custom key mode on a cluster with
more than one shard, `ReadFromRemote::addPipe` reads a shard with one `RemoteQueryExecutor` in
`PoolMode::GET_MANY`. Every replica gets its own `parallel_replica_offset` and returns its own part of
the result of the shard, and all parts arrive interleaved through one `RemoteSource` port.

The initiator's order-dependent merges assume one ordered stream per port:
- `GroupingAggregatedTransform` treats a port as past bucket b once any replica sent b + 1, pushes b,
  and the slower replica's chunk of b recreates it: `pushed bucket b twice` (a `LOGICAL_ERROR`;
  duplicated groups before ClickHouse#114523);
- the sorted merge for `ORDER BY` merges ports that are not sorted, and with one shard there is no
  merge at all, so `ORDER BY ... LIMIT` returns rows of one replica.

As decided by the owner in ClickHouse#115986 (fail closed, decided from the final plan), a new last pass of
`optimizeTreeSecondPass`, `allowReadingShardsFromSeveralReplicas`, walks from every `ReadFromRemote` to
its first consumer that is not `Expression`/`Filter`/`Union`, and allows several replicas only for a
consumer that ignores the order of its input streams: a `MergingAggregated` that is not memory bound
and either not memory efficient or without keys, an `Aggregating` that is not in order, a `Full`
sort. Anything else, including the plan root (whose consumer is outside the plan: an upper initiator,
the parent of a `Merge` child plan, a set), and any plan that is never optimized, read every shard
from one replica (`GET_ONE` sends no `parallel_replicas_count`, so that replica reads the whole shard).
`addPipe` runs in `initializePipeline`, after the optimization, so the pool mode follows the final plan.

The single-shard custom key case already reads every replica through its own `GET_ONE` executor and is
unchanged. The price is the parallelism inside a shard for order-dependent offset-mode reads.

Related: ClickHouse#115986

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-experimental Experimental Feature pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants