Repository navigation
Fix wrong results of the partial aggregation strategy in distributed query plans - #114523
Conversation
…ilds Co-Authored-By: Claude Fable 5 <[email protected]>
…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]>
|
Workflow [PR], commit [b8a88ec] Summary: ✅
AI ReviewSummaryThis 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 Missing context / blind spots
Final Verdict✅ No new findings on the current head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 41/41 (100.00%) · Uncovered code |
…licas plan rewrite too Co-Authored-By: Claude Fable 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units49 translation units recompiled, 424 s compile time in total, 49 of them have a recent master baseline. |
|
@copilot resolve the merge conflicts in this pull request |
Resolved in commit |
|
|
||
| QueryPlanStepPtr AggregatingStep::cloneAsPartial(bool produce_results_in_order_of_bucket_number) const | ||
| { | ||
| return std::make_unique<AggregatingStep>( |
There was a problem hiding this comment.
Maybe reuse the clone + setFinal(false) pattern. It tells much clearer how the new step is different from the source one.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
Co-authored-by: nickitat <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
6e9fe29 to
cdf63c6
Compare
…uted rewrites Co-Authored-By: Claude Fable 5 <[email protected]>
…a bucket twice Co-Authored-By: Claude Fable 5 <[email protected]>
|
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 |
Cherry pick #114523 to 26.7: Fix wrong results of the partial aggregation strategy in distributed query plans
…n strategy in distributed query plans
Cherry pick #114523 to 26.6: Fix wrong results of the partial aggregation strategy in distributed query plans
…n strategy in distributed query plans
…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]>
`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.
`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.
Backport #114523 to 26.7: Fix wrong results of the partial aggregation strategy in distributed query plans
Backport #114523 to 26.6: Fix wrong results of the partial aggregation strategy in distributed query plans
…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]>
The partial+merge aggregation strategy of
make_distributed_planrewrites a final aggregation into a partialAggregatingStepplus a memory-efficientMergingAggregatedStep. The memory-efficient merge consumes each input as a stream of two-level buckets in ascending order, but the rewrite keptshould_produce_results_in_order_of_bucket_number = falseon 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: duplicatedGROUP BYkeys with split aggregate states (for ClickBench Q08, a wrongCOUNT(DISTINCT UserID)).The fix, one commit each:
LogicalExchangeStep. The#if CLICKHOUSE_CLOUDguard 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).GroupingAggregatedTransform: an unannounced late bucket now fails with aLOGICAL_ERRORexception instead of silently duplicating groups.GroupingAggregatedTransformwhen the consumer needs the output in bucket order, and release the announcements of finished inputs. Covered by a gtest.should_produce_results_in_order_of_bucket_number = truewhen 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix duplicated
GROUP BYkeys in the partial aggregation strategy ofmake_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
26.8.1.1855(included in26.8and later)26.7.8.11,26.6.6.14