Repository navigation
Do not use the distributed-plan Shuffle aggregation when bucket order is promised - #116446
Conversation
… is promised An aggregation that promises to produce its results in bucket order was rejected with LOGICAL_ERROR "GroupingAggregatedTransform pushed bucket <N> twice" when make_distributed_plan chose the Shuffle strategy. tryMakeDistributedAggregation's Shuffle branch moves the original AggregatingStep wholesale under a scatter, so each of the bucket_count instances keeps should_produce_results_in_order_of_bucket_number while ordering only its own share. GatherReceiveStep restores order only from a SortDescription, and the bucket number lives in AggregatedChunkInfo::bucket_num chunk metadata rather than in a column, so no global order can be restored there. The memory-efficient merge above then receives a bucket it has already merged and its check rejects the query. The sibling PartialAggregation branch re-derives the promise for the step it clones and feeds a merge that consumes ordered per-input bucket streams. Force PartialAggregation when the step must produce results in bucket order, placed after the distributed_plan_force_shuffle_aggregation override so it wins, next to and in the style of the GROUPING SETS override which resolves the same duplication class the same way. The guard is deliberately keyed on shouldProduceResultsInBucketOrder() alone. Adding usingMemoryBoundMerging() as a second disjunct also removes Shuffle from ordinary Complete-stage aggregations that promise nothing, because enable_memory_bound_merging_of_aggregation_results defaults to 1; it is also redundant, since memoryBoundMergingWillBeUsed already requires the promise. The failure reproduces deterministically from plain SQL (5/5 before, 5/5 pass after), with output byte-identical to the same queries under make_distributed_plan = 0. The new stateless test fails on the parent commit with the exact message and asserts arming, correctness, and that Shuffle is still chosen, including under its force setting, when nothing requires bucket order. Related: ClickHouse#115986
The regression test asserted its arming on the classic shard plan: both rows carried `make_distributed_plan = 0` on the wrapper, and that value reaches the inner plan being explained too, so they proved the memory-efficient merge exists rather than that the `make_distributed_plan` rewrite ran. They now explain with `distributed = 1` and the setting stated on the inner query, which is the rewritten per-shard plan the guard acts on. Two rows are added that observe the guard rather than its consequence: the shuffle scatter is absent from the shard plan, with and without `distributed_plan_force_shuffle_aggregation`. Removing only the guard hunk and keeping the test flips both from 1 to 0, so they are not vacuous. The two execution arms now pin the force setting instead of relying on the statistics-free default choice of Shuffle, which a later estimation change could move. `distributed_plan_force_shuffle_aggregation` documented an unconditional strategy choice, which two overrides in `tryMakeDistributedAggregation` contradict: GROUPING SETS, and now an aggregation that must produce results in bucket order. The docstring states the general rule. `docs/` is generated from `Settings.cpp` and is left alone. The default, tier and type are unchanged, so there is no `SettingsChangesHistory.cpp` entry. Co-Authored-By: Claude Fable 5 <[email protected]>
…it removes Every non-execution row of the regression test was a negative or an ambient assertion: the shuffle scatter is absent, a memory-efficient merge exists, more than one shard is read. An implementation that declined to distribute the aggregation at all, returning from `tryMakeDistributedAggregation` and leaving the aggregation step un-rewritten, satisfied all of them, because a single aggregation instance also pushes no bucket twice. Two rows are added on the affected and forced shape, asserting that the plan carries the partial aggregation and its merge, each named at the site that builds it. Against a mutant that returns instead of demoting the strategy, the two new rows drop to 0 while the rows asserting the absent scatter stay at 1, so they observe a property those rows do not. The parallel replicas optimization sets the same two descriptions, and the dumped plan carries no parallel replicas read step, so the settings pinned at file scope do keep that path off. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings on this revision).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260826-043752 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260826-033200 |
|
Workflow [PR], commit [100afdd] Summary: ✅
AI ReviewSummaryThis PR fixes the rule-based Findings
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 12/14 (85.71%) · Uncovered code |
|
cc @davenger @nickitat, could you review this? The |
…tion 04367_distributed_plan_merge_scatter_multishard aggregates over a Merge table of Distributed tables. ReadFromMerge builds each child plan at the mergeable-state stage, so every child AggregatingStep carries the bucket-order promise (Planner.cpp sets it from to_stage == WithMergeableState and either distributed_aggregation_memory_efficient or enable_memory_bound_merging_of_aggregation_results, both default 1). The guard added by this PR therefore demotes those child plans from Shuffle to partial aggregation plus merge, and the pinned plan changes accordingly. The old shape was an instance of the defect this PR fixes, not a shape worth keeping: the child plan promised bucket order and let the shuffle destroy it. The query never exposed it because a single group produces no two-level buckets, so GroupingAggregatedTransform never sees a bucket twice. Measured, on this fixture: - With distributed_aggregation_memory_efficient = 0 and enable_memory_bound_merging_of_aggregation_results = 0 the promise is absent, the guard does not fire and the plan is byte-identical to the old reference. So the demotion here is conditional on the promise, not an unconditional rewrite. - The child plan still carries a ScatterExchange directly above a bucketed read in both shapes (visible with distributed_plan_optimize_exchanges = 0), which is the structure issue ClickHouse#107946 was about, so the reference update does not remove the structure this test exists to exercise. - Of the 107 stateless tests that mention make_distributed_plan, 97 pass; the other 10 fail identically on a build of the merge base, i.e. for reasons unrelated to this change. - The new reference fails on a build of the merge base and passes with the fix. Co-Authored-By: Claude Opus 5 <[email protected]>
The plan pinned by 04367_distributed_plan_merge_scatter_multishard now depends on the bucket-order promise, which holds when either distributed_aggregation_memory_efficient or enable_memory_bound_merging_of_aggregation_results is on. The stateless runner randomizes both independently (tests/clickhouse-test:1505 and :1597), so with both at 0 the guard does not fire and the plan keeps its old shape. Measured over 40 runs with randomization on: 40 pass with the setting pinned, 32 pass and 8 fail without it. The four combinations were measured on this fixture: only both-off yields the old shape, and the other three are byte-identical to the checked-in reference, so pinning one of the two is sufficient. Also wrap `GROUPING SETS` in the setting documentation added by this PR in inline code, per the repository rule in AGENTS.md. Co-Authored-By: Claude Opus 5 <[email protected]>
The two keep-shuffle controls disabled both settings that create the bucket-order promise, so what kept the shuffle in them was ambiguous: either the Complete stage or the absent settings. With both settings pinned on, only the stage can keep it, and the rows also pin the default configuration since both settings default to 1. Proven live with a mutant that keys the guard on the raw settings instead of the promise, dropping the stage term: the strengthened rows go 1 to 0 and the test fails, while the previous form of the same two rows passes on that binary. No new rows and no reference change. Co-Authored-By: Claude Opus 5 <[email protected]>
Every row asserting the shard plan ran with the promise present, so a guard demoting every non-final aggregation, rather than only a promise-carrying one, passed the test while removing the shuffle from every shard leg. One row now runs the same shard-plan query with both settings that create the promise off and the force setting on, and asserts the scatter is still there. Measured on the same binary: that query reports the scatter absent with the promise on and present with it off, which is the pair the guard's predicate straddles. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Pushed The failure was a plan reference in Re-reviewing that turned up something worth having: the new reference depends on a setting the test runner randomizes ( Correction to row 2: the claim that a promise-carrying aggregation reaches Cascades' |
| /// order: it merges by a sort description, and the bucket number is chunk metadata, not a column. | ||
| /// Shuffle is therefore impossible here, so `distributed_plan_force_shuffle_aggregation` cannot | ||
| /// apply either, as with GROUPING SETS below. | ||
| if (aggregating_step->shouldProduceResultsInBucketOrder()) |
There was a problem hiding this comment.
shouldProduceResultsInBucketOrder() is wider than the case where Shuffle is actually incorrect. Planner.cpp:494-496 sets it for both distributed_aggregation_memory_efficient and enable_memory_bound_merging_of_aggregation_results, but with distributed_aggregation_memory_efficient = 0 the initiator still builds a plain MergingAggregatedStep (InterpreterSelectQuery.cpp:2463-2474), and memoryBoundMergingWillBeUsed() cannot trigger here without in-order aggregation (MergingAggregatedStep.cpp:223-225, which make_distributed_plan rejects earlier). In that configuration Shuffle is still correct, so this guard now needlessly forces PartialAggregation and makes distributed_plan_force_shuffle_aggregation ineffective.
Can we key the demotion on the downstream merge mode that actually consumes bucket-ordered shard output, or add a focused test for distributed_aggregation_memory_efficient = 0, enable_memory_bound_merging_of_aggregation_results = 1 before narrowing the strategy?
There was a problem hiding this comment.
You are right about the boundary, and it measures out: on a build with the guard removed,
distributed_aggregation_memory_efficient = 0, enable_memory_bound_merging_of_aggregation_results = 1
keeps Shuffle and returns results byte-identical to make_distributed_plan = 0, while the guard
demotes it (by hash( 2 to 0) and the merge above the shard output is not the memory-efficient one
there (memory-efficient 0). In that one combination the demotion costs a plan shape and nothing reads
the bucket order it preserves.
I took the second option. 04878 now pins the truth table with one arm per promise source: (1, 0) and
(0, 1) each assert no shuffle plus the partial aggregation and its merge, (0, 0) keeps the shuffle,
and one further row records that the merge is not memory-efficient at (0, 1).
enable_memory_bound_merging_of_aggregation_results is pinned in the test as well, since the runner
randomizes it and the earlier arms left it open.
I am not narrowing the guard here. (0, 1) and (1, 1) are indistinguishable from the step: the promise
is A || B while usingMemoryBoundMerging is B, so separating them means reading
distributed_aggregation_memory_efficient at the site, which is the setting-versus-invariant coupling
this guard removes, and the difference is a plan choice rather than a correctness outcome. The new arms
pin the current behaviour, so a later narrowing is a deliberate reference update.
On distributed_plan_force_shuffle_aggregation being ineffective: that override is intended and this PR
documents it in the setting's own description, the same way the pre-existing GROUPING SETS override
already behaves. Your wording is fair for (0, 1) though, where the "cannot produce a correct result"
premise does not hold.
The Stateless tests (distributed plan) red on the previous head was mine and is fixed in the same
push: that flavour enables serialize_query_plan, and EXPLAIN PLAN distributed = 1 then prints the
shard plan as it was shipped rather than as the shard rewrote it.
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 units8 translation units recompiled, 29 s compile time in total, 8 of them have a recent master baseline. |
The Stateless tests (distributed plan) flavor enables serialize_query_plan for
every test through tests/config/users.d/distributed_plan.xml, and four of the
test's plan assertions failed there: the shard plan an initiator ships is built
before makeDistributed rewrites it, and ReadFromRemote::describeDistributedPlan
prints that shipped plan locally instead of asking the shard to explain, so the
rewrite the rows assert is not in the output. The shard applies the rewrite after
it deserializes and resolves storages, which is why the aggregation itself still
ran and only the plan rows moved.
Two of the affected rows assert that a token is absent, so they were passing
without observing anything: on a build with the guard removed the "by hash("
count is 2 with serialize_query_plan = 0 and 0 with it on. Pinning the setting
makes them read the rewritten plan again. Nothing about the defect depends on the
setting - with the guard removed the aggregation fails with "pushed bucket N
twice" in both modes, on a fresh server per arm - so the new FORMAT Null row
keeps that side covered in every flavor now that the setting is pinned.
The last two rows pin the boundary that distributed_aggregation_memory_efficient
= 0, enable_memory_bound_merging_of_aggregation_results = 1 sits on: the promise
is set from either setting, so the shuffle is demoted, while the merge above the
shard output is not the memory-efficient one and no consumer reads the preserved
bucket order. Measured on that combination: the guard removes a shuffle plan
("by hash(" 2 -> 0) whose results are byte-identical to the undistributed plan.
Validation: 40/40 with the six relevant settings randomized (both promise
settings, serialize_query_plan, prefer_localhost_replica,
optimize_aggregation_in_order, max_threads); with the pin removed,
serialize_query_plan = 1 fails 12/12 and 0 passes 12/12.
…OUPING SETS The memory-bound-only group only asserted that tokens are absent, so an implementation that declined the aggregation rewrite for that setting combination would have satisfied it: it has neither `by hash(` nor a memory-efficient merge. Two rows now name the strategy positively, as the group above already does. Measured on `distributed_aggregation_memory_efficient = 0, enable_memory_bound_merging_of_aggregation_results = 1`: `Aggregating (partial)` and `MergingAggregated (merge)` are 2 on this branch and 0 on a build with the guard removed, where `by hash(` is 2 instead. The comment on the `serialize_query_plan = 1` row now says that it pins the outcome rather than the strategy. No explain observes a rewrite made on the shard side: `EXPLAIN PLAN distributed = 1` prints the plan as it was shipped, and `EXPLAIN PIPELINE distributed = 1` throws `NOT_IMPLEMENTED` with `serialize_query_plan = 1` (`ReadFromRemote.cpp:990`). The row is still specific to this defect: with the guard removed it fails with "pushed bucket N twice". `GROUPING SETS` in the guard comment is now inline code, as `AGENTS.md` requires for literal SQL names. An earlier round of this branch declined that same request on the grounds that no such repository rule exists; that was wrong, the rule is at `.claude/CLAUDE.md:7` and predates this branch. The same round declined the request to put the supplied report URL in the commit message, and that was wrong too, for the same reason: `.claude/CLAUDE.md:169`. Both links, per that rule: Failing check this commit answers: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116446&sha=c5ac60fd8dcd6e81e274126b140fb9828bbb54e5&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%2C%20selected%20tests%29 ClickHouse#116446 Report the fix was written for: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116259&sha=2e55a2277e66c6762e444c2cb6dc18a585cbfc5b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 ClickHouse#116259 Validation: 40/40 with the promise settings, `serialize_query_plan`, `prefer_localhost_replica`, `optimize_aggregation_in_order` and `max_threads` randomized; the guard-removed build reddens the file in both `serialize_query_plan` modes, on a fresh server per arm.
`enable_memory_bound_merging_of_aggregation_results` is randomized by the runner (`tests/clickhouse-test:1597`) and every arm that set only `distributed_aggregation_memory_efficient = 1` left it open, so those arms did not say which of the two settings they exercised, and a guard tied only to the randomized one could pass. It is pinned in the session block now, and the two promise sources have an arm each: `(1, 0)` and `(0, 1)`, each asserting the whole demoted shape in one row (no shuffle, plus the partial aggregation and its merge) so a plan left undistributed does not satisfy them. Measured standalone on those two combinations: both rows are 1 on this branch and 0 on a build with the guard removed, where `by hash(` is 2 instead. The four rows they replace are folded into them, so the truth table is now `(0,0)` keeps the shuffle and `(1,0)`, `(0,1)`, `(1,1)` demote. Report this branch is fixing, per `AGENTS.md`: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116259&sha=2e55a2277e66c6762e444c2cb6dc18a585cbfc5b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 ClickHouse#116259 Validation: 40/40 with both promise settings, `serialize_query_plan`, `distributed_plan_force_shuffle_aggregation`, `prefer_localhost_replica`, `optimize_aggregation_in_order` and `max_threads` randomized; the guard-removed build reddens the file in both `serialize_query_plan` modes, one fresh server per arm.
Measured against a build whose aggregation rewrite returns without transforming the step: the row passes in both `serialize_query_plan` modes, so it does not separate the demotion from an aggregation left unrewritten above the gather. The rows above separate the two, and they can only do it when the plan is not shipped, which the comment now says. Report this branch is fixing, per `AGENTS.md`: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116259&sha=2e55a2277e66c6762e444c2cb6dc18a585cbfc5b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 ClickHouse#116259
CI finish ledger - 100afddCI is fully finished at this commit and no check failed, so no ledger row is owed. Evidence: no check queued or in progress; 175 check runs resolve to 157 success and 18 skipped, Session id: cron:our-pr-ci-monitor:20260826-163000 |
|
We can obviously just disable it, but it doesn't look like a good solution. @davenger, Sasha, wdyt, should we merge the quick fix or rather implement some proper support for this? |
|
The guard is a stopgap, not the design, and the call is yours. Here is what each option costs, so it is cheap to make. The guard, while it stands. It fires only on a step carrying the bucket-order promise, and The bucket-aware collapse. Of the two shapes, this is the one that does not need the plan to own the initiator side, and the pieces are in place. I can implement the transform, in this PR or a follow-up. Tell me which you prefer, and whether the guard should land meanwhile or be dropped so the transform is the only change. |
| SELECT countIf(explain ILIKE '%by hash(%') = 0 | ||
| AND countIf(explain ILIKE '%Aggregating (partial)%') > 0 | ||
| AND countIf(explain ILIKE '%MergingAggregated (merge)%') > 0 FROM |
There was a problem hiding this comment.
@groeneai It is inconvenient to debug failures of such checks that count lines by patterns in EXPLAIN output. It's much more human-friendly to pin the full EXPLAIN output in .refernce
There was a problem hiding this comment.
Agreed, and thanks: counting matched lines is the wrong shape for a plan assertion, and it tells you nothing when it goes red. #116446 is merged, so I will do this in a follow-up PR against master and link it here.
Shape I will use, matching 04869_distributed_plan_partial_aggregation_bucket_order: print the plan and pin it, i.e. replace each SELECT count() ... FROM (EXPLAIN ...) WHERE explain ILIKE '%...%' arm with the EXPLAIN itself. The random database name is normalized to default in stdout before the reference comparison (tests/clickhouse-test:3957), so the plan text is pinnable as it is printed. I am converting the pattern-counting arms only; the behavioural rows stay as they are (the FORMAT Null queries that must not hit the duplicate-bucket rejection, and the two result-equality rows), unless you want those touched too.
One thing the pinned output has to carry over: the plan text here depends on settings the runner randomizes, mainly distributed_aggregation_memory_efficient and enable_memory_bound_merging_of_aggregation_results, so the explicit SET pins stay. Without them 8 of 40 randomized runs diverged when I measured it on this PR. I will validate the new reference over 50 randomized runs before opening the follow-up.
There was a problem hiding this comment.
Done, #120757.
The 12 count() ... ILIKE rows collapse onto the 7 distinct explain queries they came from, each plan pinned in .reference behind a SELECT '-- label'; marker, in the shape 04869 already uses. The behavioural rows and every SET pin are untouched.
Two DDL pins were needed to make the pinned output deterministic, index_granularity_bytes = 0 and min_bytes_for_wide_part = 0: the two actions = 1 blocks print Parts:/Granules:, and the runner randomizes what those depend on. 50 of 50 randomized runs are green, and reverting the guard reds 4 of the 7 blocks, while the 3 asserting that the shuffle stays are byte-identical.
Resolve the cherry-pick of #116446 for 26.6: - Drop `04367_distributed_plan_merge_scatter_multishard`, which does not exist on this branch, so the PR's update to its expectations has nothing to apply to. - Drop `SET explain_query_plan_default = 'legacy'` from the new test: the setting and the second renderer it selects are both master-only, and this branch renders only the legacy plan the test's `ILIKE` rows match. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Cherry pick #116446 to 26.6: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
Resolve the cherry-pick of #116446 for 26.7: drop `04367_distributed_plan_merge_scatter_multishard`, which does not exist on this branch, so the PR's update to its expectations has nothing to apply to. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Cherry pick #116446 to 26.7: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
…regation when bucket order is promised
…regation when bucket order is promised
Backport #116446 to 26.8: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
Backport #116446 to 26.7: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
Backport #116446 to 26.6: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
…huffle aggregation when bucket order is promised
…order_promise Requested in review on the merged PR ClickHouse#116446: ClickHouse#116446 (comment) The test asserted its plan claims with 12 rows of the form `SELECT count() ... FROM (EXPLAIN ...) WHERE explain ILIKE '%...%'`. Each row projects the plan onto one bit and discards it before the comparison, so a red row prints `1 -> 0` and nothing about the plan, and reading the failure means rebuilding and re-running the explain by hand. The same test is red on the 26.6 backport ClickHouse#120640 right now, with exactly that output. Those 12 rows use only 7 distinct explain queries, differing solely in their `SETTINGS` clause, so they collapse onto 7 pinned plans, each behind a `SELECT '-- label';` marker line so the reference stays navigable. Every `SET` pin and every behavioural row is unchanged: the three `FORMAT Null` rows that must not hit the duplicate-bucket rejection, and the two `HAVING k = 7` result-equality rows. Each block keeps the smallest flag set its claims need. Five are a plain `EXPLAIN`, since the step descriptions they read (`by hash(...)`, `partial`, `merge`) are printed without `actions = 1`. The two asserting the merge mode do need it, because `Mode: memory-efficient` is printed only by `MergingAggregatedStep::describeActions`; those two add `compact = 1`, which makes `skip_expressions` walk past every `Expression` step in the initiator plan and, through `ExplainPlanOptions::toSettingsChanges`, in both shard plans, so their `Actions:`/`Positions:` dumps stay out of the reference. `pretty = 1` is not usable here, as it cannot represent per-shard plans. `index_granularity_bytes = 0` and `min_bytes_for_wide_part = 0` are new in the DDL. The two `actions = 1` plans print `ReadFromMergeTree`'s granule count, and the runner randomizes both of that number's inputs. `index_granularity_bytes` is drawn from `[1024, 30 MiB]` (`tests/clickhouse-test:2006`), and once it falls below `index_granularity` times the row size the adaptive byte quotient replaces the fixed 256 rows per granule: measured on this 16-byte fixture, 2048 prints `Granules: 1563` and 1024 prints 3125, against 782 at 4096 and above. The 100 KiB floor that hides the window applies only to sanitizer, debug and coverage builds (`:2096-2103`), so a release-flavour run is the exposed one. `min_bytes_for_wide_part` moves the same number by one between the two part formats. With adaptive sizing off the count is `ceil(rows / index_granularity)` for any block width and either format, which also closes the row-width exposure through the randomized `enable_block_number_column` and `enable_block_offset_column`. A table setting in the DDL holds against the runner's injection, which skips settings the query already sets, and against the server default alike, which is why the `index_granularity = 256` this reference also depends on already survives there. Validation: removing the guard hunk ClickHouse#116446 added at `makeDistributed.cpp:715-721` makes 4 of the 7 blocks red, with `ShuffleExchange (by hash([__table1.k]))` reappearing once per shard plan, while the 3 blocks asserting that the shuffle stays when nothing promises bucket order are byte-identical; the reference reds on that regression and only there. The granule pins are proven through the runner's own merge-tree injection seam: `--merge-tree-settings "--index_granularity_bytes 2048"` passes with them and reds `Granules: 782 -> 1563` on all four lines without them. 50 of 50 runs green with settings randomization on (161-196 settings drawn per query, 50 distinct randomized merge-tree tails, part format Wide in all 50). The reference is generated from the runner's own stdout, not pasted by hand. Co-Authored-By: Claude Opus 5 <[email protected]>
|
It reproduces, but not through the route #116446 closed, and not from your PR. The abort on That last setting picks the planner: The fix for the Cascades route is #119814, which is not mine: it adds that check, and pins For scale, so you can discount it on your PR: this signature (STID 3994-4c1d) has 192 failures over 146 distinct PRs, 18 distinct master commits and 21 check flavours in the last 30 days. Two recent master ones: amd_debug at |
…optimizer A shard of a plain distributed query plans its aggregation to the `WithMergeableState` stage, and with `distributed_aggregation_memory_efficient` or `enable_memory_bound_merging_of_aggregation_results` that `AggregatingStep` promises the initiator's merge to deliver its two-level buckets in order. The initiator reads each shard as one stream. With `enable_cascades_optimizer` (the stress test turns it on) the Cascades `AggregationImplementation` rule offered the non-final aggregation only at the full node count, and the `DistributionEnforcer` gathered the instances straight into that stream. Each instance orders only its own share, so the initiator saw a bucket twice and failed with `Logical error: 'GroupingAggregatedTransform pushed bucket 3 twice'` (test 04878 under the stress runner's client options). Now a non-final aggregation that promises bucket order, and is not the partial half of a two-stage split, runs on a single node, and `TwoStageAggregationTransformation` splits such a step too, with a non-final merge that restores the bucket order over the gathered partials - the same demotion the rule-based rewrite got in ClickHouse#116446. The partial half of a split is marked on its `GroupExpression`, so it keeps its multi-node variants and is not split again. An aggregation in order stays on a single node, as in the rule-based planner. Test 05210 pins the plan shape and the results under the Cascades optimizer. Test 04878 reads the plan of the rule-based rewrite, so it now turns the Cascades optimizer off explicitly. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=64bddd33323e3583dec578d27135bbb6e5359675&name_0=MasterCI&name_1=Stress%20test%20%28arm_release%29 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Related: #115986
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
LOGICAL_ERROR: GroupingAggregatedTransform pushed bucket N twicewhenmake_distributed_planpicks theShuffleaggregation strategy while the aggregation must produce results in bucket order (for example withdistributed_aggregation_memory_efficient). It is now planned as a partial aggregation plus a merge.Description
An aggregation that must produce results in bucket order was rejected with
LOGICAL_ERROR: GroupingAggregatedTransform pushed bucket <N> twicewhenmake_distributed_planchose the
Shufflestrategy.Root cause: that branch moves the
AggregatingStepunchanged under a scatter, so eachbucket_countinstance keeps the promise while ordering only its own share, and the gather merges by a sort
description, which cannot express a bucket number held in chunk metadata. The merge above then receives
a bucket it already merged and rejects the query.
The fix forces the sibling
PartialAggregationstrategy when the step must produce results in bucketorder; that branch re-derives the promise and feeds a merge built for ordered per-input bucket streams.
The guard sits next to the existing
GROUPING SETSoverride, which resolves the same duplication classthe same way; as there,
distributed_plan_force_shuffle_aggregationcannot apply.The promise is set at the
WithMergeableStatestage when eitherdistributed_aggregation_memory_efficientorenable_memory_bound_merging_of_aggregation_resultsison, and both default to
1, so this narrowsShuffleon the shard leg of anyremote()orDistributedquery. AComplete-stage aggregation promises nothing and keepsShuffle, includingunder the force setting; the test pins both directions. A bucket-aware gather merge would keep
Shuffle, but needs a new exchange transform.Not covered here:
enable_cascades_optimizer = 1skips the rule-based path holding this guard(
optimizeTree.cpp:396), and Cascades picks the strategy through its own rules, which this change doesnot touch. That setting defaults to
falsetoo.#115487and#114523are merged and present here; this path is outside their scope, andmake_distributed_planisEXPERIMENTALand defaults tofalse. The failure reproduces from plain SQLbefore the change (5/5) and passes after (5/5), output byte-identical to
make_distributed_plan = 0;the new test fails on the parent commit with that message.
Why the 04367_distributed_plan_merge_scatter_multishard reference changes, and why that is not a weakening
ReadFromMergebuilds each child plan at the mergeable-state stage, so every childAggregatingStepin that fixture carries the promise and the guard demotes it.
The query never exposed it because a single group produces no two-level buckets, so
GroupingAggregatedTransformnever sees the same bucket twice.distributed_aggregation_memory_efficient = 0andenable_memory_bound_merging_of_aggregation_results = 0the guard does not fire and the plan isbyte-identical to the old reference.
#107946is about is intact: withdistributed_plan_optimize_exchanges = 0thechild plan still carries a
ScatterExchangedirectly above a bucketed read in both shapes.make_distributed_plan, 97 pass and the other 10 failidentically on a build of the merge base. The new reference fails on that build and passes with the
fix.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116259&sha=2e55a2277e66c6762e444c2cb6dc18a585cbfc5b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Workflow [PR]
Sync PR [sync-upstream/pr/116446]
Version info
26.8.7.18,26.7.11.14,26.6.9.15