Skip to content

Do not use the distributed-plan Shuffle aggregation when bucket order is promised - #116446

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-grouping-aggregated-bucket-pushed-twice-3rd-path
Sep 13, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-grouping-aggregated-bucket-pushed-twice-3rd-path

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115986

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix LOGICAL_ERROR: GroupingAggregatedTransform pushed bucket N twice when make_distributed_plan picks the Shuffle aggregation strategy while the aggregation must produce results in bucket order (for example with distributed_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> twice when make_distributed_plan
chose the Shuffle strategy.

Root cause: that branch moves the AggregatingStep unchanged under a scatter, so each bucket_count
instance 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 PartialAggregation strategy when the step must produce results in bucket
order; 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 SETS override, which resolves the same duplication class
the same way; as there, distributed_plan_force_shuffle_aggregation cannot apply.

The promise is set at the WithMergeableState stage when either
distributed_aggregation_memory_efficient or enable_memory_bound_merging_of_aggregation_results is
on, and both default to 1, so this narrows Shuffle on the shard leg of any remote() or
Distributed query. A Complete-stage aggregation promises nothing and keeps Shuffle, including
under 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 = 1 skips the rule-based path holding this guard
(optimizeTree.cpp:396), and Cascades picks the strategy through its own rules, which this change does
not touch. That setting defaults to false too.

#115487 and #114523 are merged and present here; this path is outside their scope, and
make_distributed_plan is EXPERIMENTAL and defaults to false. The failure reproduces from plain SQL
before 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

ReadFromMerge builds each child plan at the mergeable-state stage, so every child AggregatingStep
in that fixture carries the promise and the guard demotes it.

  • The old plan was an instance of this defect: it 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 the same bucket twice.
  • The demotion is conditional on the promise, not unconditional: with
    distributed_aggregation_memory_efficient = 0 and
    enable_memory_bound_merging_of_aggregation_results = 0 the guard does not fire and the plan is
    byte-identical to the old reference.
  • The structure issue #107946 is about is intact: with distributed_plan_optimize_exchanges = 0 the
    child plan still carries a ScatterExchange directly above a bucketed read in both shapes.
  • Scope: of the 107 stateless tests naming make_distributed_plan, 97 pass and the other 10 fail
    identically 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

  • Backported to: 26.8.7.18, 26.7.11.14, 26.6.9.15

groeneai and others added 3 commits August 25, 2026 23:11
… 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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings on this revision).
This is the last of 6 fix rounds, so the tree is published as it stands and the AGREE rows
below are recorded rather than fixed.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test does not separate stage-derived bucket order from the two settings that feed it: every affected arm sets distributed_aggregation_memory_efficient, and both Complete-stage controls clear both settings AGREE, not fixed True, and bounded. The over-broad guard it names (reject Shuffle whenever either setting is on) is already caught deterministically: both settings default to 1, and five in-tree artifacts assert a Shuffle plan at default settings while pinning neither, including 03394_distributed_shuffle_join_with_aggregation.reference and four expected_plan assertions in test_distributed_plan_replicated_merge_tree. The residual case is inert: with memory-bound merging only, the initiator derives the same setting, builds no memory-efficient merge and so consumes no order, while the path that would consume it needs a non-empty group_by_sort_description (MergingAggregatedStep.cpp:223-226), i.e. in-order aggregation, on which this guard throws rather than demotes. Cheap improvement if this code is revisited: pin both settings to 1 in the Complete-stage controls.
2 ⚠️ From my own review, outside this diff: the Cascades planner has its own Shuffle-applicability predicate, isShuffleApplicable (Cascades/Rules/AggregationImplementations.cpp:64-70), with no bucket-order term AGREE, not fixed Read, not executed; I am not claiming a reproduction. Verified: that predicate tests keys.empty, isGroupingSets, overflow_row and max_rows_to_group_by but not shouldProduceResultsInBucketOrder; checkStepSupportedByCascades rejects inOrder and reads from remote shards, so a shard-side plan over a local MergeTree at WithMergeableState reaches it; addAlternative clones the step, so the promise survives. The two-phase Cascades path is unaffected (:337 forwards the promise into the merge it builds). The combination is uncovered in both directions, since 04513_cascades_two_phase_aggregation_bucket_order.sql reads a local table and so never sets the promise. Both gating settings are EXPERIMENTAL and default false. Left to that planner's owner; I am not opening a follow-up.
3 💡 GROUPING SETS is not wrapped in inline code in the appended setting description (Settings.cpp:9007) AGREE, not fixed The convention is real and predates this branch (.claude/CLAUDE.md, which AGENTS.md symlinks). I raised the same nit independently. The setting's pre-existing first line is unbackticked the same way, so both lines are best made consistent together.
4 💡 The commit messages omit the CI report URL and the pull request URL DISAGREE The provenance requirement is on the description, which carries the full canonical report URL and a visible Related: #115986; commit 250f792172a1650 also carries the issue URL in its trailer. The other link would be to the carrier pull request whose run surfaced this defect rather than to a fix, and linking it from a commit creates the cross-reference between unrelated pull requests I was asked not to create.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE carries recorded evidence and is terminal per finding.

Session id: cron:clickhouse-review-slot-9:20260826-043752

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 5/5 from plain SQL, no fuzzer. SELECT k FROM remote('127.0.0.{2,3}', db, t) GROUP BY ALL over a 200k-row / 50k-key MergeTree, with make_distributed_plan=1, distributed_plan_execute_locally=1, distributed_aggregation_memory_efficient=1, group_by_two_level_threshold=10000, group_by_two_level_threshold_bytes=1, max_threads=16, distributed_plan_default_shuffle_join_bucket_count=2, distributed_plan_max_rows_to_broadcast=0, use_statistics=0, enable_parallel_replicas=0, enable_parallel_blocks_marshalling=0. Previously reproducible only under the targeted AST fuzzer.
b Root cause explained? Yes. tryMakeDistributedAggregation's Shuffle branch moves the original AggregatingStep unchanged 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 is AggregatedChunkInfo::bucket_num chunk metadata, so no global order is restored. The memory-efficient merge then receives an already-merged bucket and GroupingAggregatedTransform::pushData rejects it.
c Fix matches root cause? Yes, at the plan-rewrite layer where the contradiction is created, not at the detector. strategy = PartialAggregation when shouldProduceResultsInBucketOrder() holds, mirroring the GROUPING SETS override three lines away which resolves the same duplication class the same way. The detector at MergingAggregatedMemoryEfficientTransform.cpp:62-63 is unchanged.
d Test intent preserved / new tests added? New stateless test 04878_distributed_plan_shuffle_bucket_order_promise.sql (SQL, not gtest; no no-parallel, names scoped to currentDatabase()). Ten assertions: two arming rows on the rewritten per-shard plan (EXPLAIN PLAN actions = 1, distributed = 1), two rows observing the guard at its own site (the shuffle scatter is absent, with and without distributed_plan_force_shuffle_aggregation), two rows asserting the strategy it selects instead (MergingAggregated (merge) and Aggregating (partial), each named at the site that builds it), two execution arms with the strategy pinned by the force setting so they do not depend on the statistics-free default, and a result comparison against make_distributed_plan = 0. Two keep-Shuffle control rows keep the guard from being over-broad. No existing test weakened.
e Both directions demonstrated? Yes. Carrier query: 5/5 abort on the parent commit (frames :123 x4 and :137 x1, both chunks_map consumers), 5/5 pass after. The whole test fails on the parent commit with Logical error: 'GroupingAggregatedTransform pushed bucket N twice' and is green 50/50 after. The plan rows are proven live independently of the aborting arms, by two mutants: with only the guard hunk reverted, the two scatter-absent rows flip from 1 to 0 before the abort is reached; with the guard's demotion replaced by an early return, the two strategy rows flip from 1 to 0 while the scatter-absent rows stay at 1, so each pair observes something the other does not.
f Fix is general across code paths? Yes. shouldProduceResultsInBucketOrder is consulted in this file only inside tryMakeDistributedAggregation; tryMakeDistributedJoin and tryMakeDistributedSorting never set or read the promise, and sorting's gather is constructed with a sort_description so its order restoration is real. Both chunks_map push arms were observed reproducing and both are fixed by the same guard, because it removes the contradiction rather than guarding a site.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for datatypes: this is planner strategy selection on bucket_num bookkeeping, type-agnostic with no storage or on-disk surface. Across the relevant parameter matrix it was measured: distributed_aggregation_memory_efficient on/off, enable_memory_bound_merging_of_aggregation_results on/off, distributed_plan_force_shuffle_aggregation on/off, Complete and WithMergeableState stages, one and two producers.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, and no default, tier or type changed, so no SettingsChangesHistory.cpp entry; only the description string of distributed_plan_force_shuffle_aggregation is amended, to state that the strategy cannot be forced where it would be incorrect (which was already true of GROUPING SETS before this change). docs/ is generated from Settings.cpp and is not hand-edited. No serialization or protocol change. The only behaviour change is which strategy an affected plan picks, and those plans previously failed. make_distributed_plan is EXPERIMENTAL and defaults to false.
i Invariants and contracts preserved? Yes. The restored invariant is the one the transform documents: each two-level bucket is pushed once, and no bucket's data arrives after it was pushed. PartialAggregation already re-derives the promise for the step it clones, so no new contract is introduced. Results verified byte-identical to the make_distributed_plan = 0 plan on both shapes (50000 rows over 50000 distinct keys), so the fix neither loses nor duplicates groups. The SUPPORT_IS_DISABLED throw added for the in-order case matches the adjacent GROUPING SETS handling of the same impossibility.

Session id: cron:clickhouse-impl-slot-6:20260826-033200

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [100afdd]

Summary: ✅


AI Review

Summary

This PR fixes the rule-based make_distributed_plan path that could route a bucket-ordering aggregation through Shuffle and trip LOGICAL_ERROR: GroupingAggregatedTransform pushed bucket N twice, and the new stateless coverage is strong on the default promise-bearing case. I do not think it is ready to approve yet because the current guard also removes Shuffle in a setting combination the new test itself shows is still correct, so the change now regresses a user-facing strategy override without a correctness benefit.

Findings
  • ⚠️ Majors
    • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116446#discussion_r3860878834] [src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:595, src/Core/Settings.cpp:9024, tests/queries/0_stateless/04878_distributed_plan_shuffle_bucket_order_promise.sql:149-164] The new guard is still wider than the case where Shuffle is actually unsafe. The new regression test now pins distributed_aggregation_memory_efficient = 0, enable_memory_bound_merging_of_aggregation_results = 1 and explicitly asserts that this path has no memory-efficient merge above the shard output, yet makeDistributed still forces PartialAggregation there. That suppresses distributed_plan_force_shuffle_aggregation and changes the plan shape in a configuration where correctness does not depend on bucket-ordered shard output. The updated setting description compounds it by telling users the override is ignored only where Shuffle "cannot produce a correct result", which is not true for this pinned branch of the matrix.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: either narrow the new guard to the correctness-critical cases, or document the broader (distributed_aggregation_memory_efficient = 0, enable_memory_bound_merging_of_aggregation_results = 1) demotion precisely enough that the setting description no longer claims a correctness reason the test disproves.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 12/14 (85.71%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @nickitat, could you review this? The Shuffle branch of tryMakeDistributedAggregation moves the AggregatingStep unchanged under a scatter, so every instance keeps its promise to produce results in bucket order while ordering only its own share, and the gather cannot put a global order back because it merges by a sort description while the bucket number is chunk metadata, so the memory-efficient merge above rejects a bucket it has already merged. The guard demotes such an aggregation to PartialAggregation, placed next to and in the style of the GROUPING SETS override that resolves the same duplication class.

groeneai and others added 4 commits August 26, 2026 06:29
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed c5ac60fd8dcd6e8 for the Fast test failure on e5c881c9, plus a correction to my comment above.

The failure was a plan reference in 04367_distributed_plan_merge_scatter_multishard, and it is this change's own output: ReadFromMerge builds its child plans at the mergeable-state stage, so they carry the bucket-order promise and the guard demotes them. With both settings that create the promise turned off, that fixture's plan is byte-identical to the old reference, so the reference was stale rather than the guard too wide, and the ScatterExchange above a bucketed read that #107946 is about is present in both shapes. The rest is in the description.

Re-reviewing that turned up something worth having: the new reference depends on a setting the test runner randomizes (tests/clickhouse-test:1505 and :1597), so it is now pinned in the test's own SET block. With randomization on, 40 of 40 runs pass with the pin and 8 of 40 fail without it. I also took the improvement row 1 above suggested, pinning both promise settings on in the Complete-stage controls, and added one row asserting the shard plan keeps the scatter when the promise is absent.

Correction to row 2: the claim that a promise-carrying aggregation reaches Cascades' isShuffleApplicable is wrong. The promise requires WithMergeableState, while final is to_stage > WithMergeableState (Planner.cpp:490-496), so such a step is non-final and AggregationImplementations.cpp:242-251 returns from the non-final branch before that predicate is consulted. Cascades cannot select Shuffle for it. What this change genuinely does not reach is that Cascades selects the strategy through its own rules at all, and enable_cascades_optimizer defaults to false.

/// 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())

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 100afdd89 with master a4311d3e6 (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 710.31 MiB 707.27 MiB -3.04 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

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

Job report

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
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 100afdd

CI 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,
with Config Workflow, Style check, Fast test, Quick functional tests and Finish Workflow
all green. praktika result_pr.json reports the root as OK over 176 nodes (157 OK,
19 SKIPPED, zero dropped and zero failing leaves). All five Stateless tests (*, flaky check)
arms are green, and Bugfix validation is green on functional tests for both architectures and on
unit tests, so the regression test in this PR does fail without the change. A CIDB query at this
commit returns zero FAIL/ERROR rows against a control of 304,373 rows over 158 checks at the
same commit, so that zero is a real filtered subset rather than an empty query. The 18 skips are
digest skips for job families this diff does not touch (Performance Comparison (amd_release, ...),
Bugfix validation (integration tests, ...), Integration tests (amd_asan_ubsan, flaky),
Docs check (Mintlify), Dockers Build, Build Toolchain (PGO, BOLT), PromQL Compliance,
Keeper Stress Tests (PR)).

Session id: cron:our-pr-ci-monitor:20260826-163000

@nickitat

nickitat commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

We can obviously just disable it, but it doesn't look like a good solution.

❯ cool, but can we make shuffle not multiplex within a port

Inside one pipeline it already doesn't. The gather keeps one port per instance:

for (size_t i = 0; i < num_buckets; ++i)
    pipes.push_back(Pipe(settings.exchange_lookup->createSource(output_header, ExchangeStreamId(exchange_id, i, 0))));
pipeline.init(Pipe::unitePipes(std::move(pipes)));      // GatherReceiveStep.cpp:26-31 — N ports, no resize

unitePipes puts the sources side by side. That is why the Complete-stage shuffle plan is fine, and it is also exactly what the PartialAggregation branch relies on: it puts the MergingAggregated (merge) directly above the gather node (makeDistributed.cpp:660), so GroupingAggregatedTransform is constructed with pipe.numOutputPorts() = bucket_count ports, one per instance, each monotone. The demotion the PR does isn't just "another strategy" — it is the shape where the gather's ports reach a bucket-aware consumer un-multiplexed.

The multiplexing in the failing case happens somewhere else: at the remote() connection. A shard returns one block sequence per connection, so whatever the shard's pipeline looks like internally, it is collapsed to a single stream by an order-oblivious resize before it goes on the wire, and the initiator's merge gets one port per shard — not per instance:

bucket_count=2 -> GroupingAggregatedTransform 2 → 1
bucket_count=4 -> GroupingAggregatedTransform 2 → 1
bucket_count=8 -> GroupingAggregatedTransform 2 → 1

So "don't multiplex within a port" has two real realizations.

Move the boundary so the gather's ports reach the merge. If the final merge lives above the gather in the same plan, there is no wire between them and nothing to collapse — GroupingAggregatedTransform gets shards × bucket_count monotone ports, which is literally the normal multi-replica case it was built for, with no new transform at all. That is what PartialAggregation does today, and what a Shuffle plan would do if the distributed plan owned the initiator side of the aggregation instead of handing a mergeable-state result back through remote(). The bug lives precisely at the seam between the new distributed planner and the old distributed protocol: the shard leg is rewritten in isolation, the consumer is the classic initiator merge, and the two are connected by a one-stream wire.

Or keep the wire and make the collapse bucket-aware. The instances hold disjoint key sets, so nothing has to be merged — the ports just have to be concatenated in bucket order: hold each bucket until every live instance is past it, emit all its chunks together, and announce anything you still have to push late via out_of_order_buckets (which survives the wire, BlockInfo.h:39). That is the small transform from before, and GatherReceiveStep already has the slot where MergingSortedTransform goes for maintain_sort_description.

One variant that looks like it avoids the problem but doesn't really: making the scatter partition by the same function as the two-level bucketing, so each instance owns a disjoint set of bucket ids. It does remove the duplicate — each bucket then appears once on the wire — so the LOGICAL_ERROR goes away, but the stream is still non-monotone, so the merge keeps deciding buckets are complete before they arrive and they only get pushed on the all_inputs_finished path; correct results, but the memory bound the memory-efficient merge exists for is gone. It also couples the scatter to the aggregation method's hash (mapToRange of the key hash vs (hash >> 24) & 255 of the method's own hash, different per key type) and does nothing when states stay single-level.

So: yes, but the fix is to remove the wire from between the gather and the merge, not to change the gather. Until then the guard is the correct stopgap.

@davenger, Sasha, wdyt, should we merge the quick fix or rather implement some proper support for this?

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

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 Planner.cpp:494-496 sets that exactly at WithMergeableState when either distributed_aggregation_memory_efficient or enable_memory_bound_merging_of_aggregation_results is on (both default to true). So with make_distributed_plan = 1 a shard leg entered through remote() or Distributed loses Shuffle for its aggregation, while a Complete-stage plan keeps it, including under distributed_plan_force_shuffle_aggregation. Beyond that plan choice the only behaviour change is a new SUPPORT_IS_DISABLED where partial aggregation is unavailable (aggregation in order). The same shape today throws LOGICAL_ERROR at MergingAggregatedMemoryEfficientTransform.cpp:63, so it trades a rejected query for a slower plan, under a setting that is EXPERIMENTAL and defaults to false. In source it is one condition in tryMakeDistributedAggregation plus one doc line, deleted verbatim once real support lands.

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. GatherReceiveStep.cpp:34-50 is already the slot where a transform goes when the gather has to preserve an order (MergingSortedTransform under maintain_sort_description). The scatter sends every row of a key to one instance (makeDistributed.cpp:590), so the instances hold disjoint key sets and their buckets only have to be concatenated in bucket order, not merged. Late buckets can be announced across the exchange without a new protocol field: out_of_order_buckets is a serialized BlockInfo field (BlockInfo.h:39), and NativeCompressedSink.cpp:59, which is what GatherSendStep writes through, already copies it out of AggregatedChunkInfo. That is one transform plus a flag on the gather step. Removing the wire instead means planning the initiator side of the aggregation as well, which is a much larger change.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
Comment on lines +146 to +148
SELECT countIf(explain ILIKE '%by hash(%') = 0
AND countIf(explain ILIKE '%Aggregating (partial)%') > 0
AND countIf(explain ILIKE '%MergingAggregated (merge)%') > 0 FROM

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.

@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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

PedroTadim added a commit that referenced this pull request Sep 17, 2026
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]>
PedroTadim added a commit that referenced this pull request Sep 17, 2026
Cherry pick #116446 to 26.6: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
PedroTadim added a commit that referenced this pull request Sep 17, 2026
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]>
PedroTadim added a commit that referenced this pull request Sep 17, 2026
Cherry pick #116446 to 26.7: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
robot-clickhouse added a commit that referenced this pull request Sep 17, 2026
robot-clickhouse added a commit that referenced this pull request Sep 17, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 17, 2026
Backport #116446 to 26.8: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
clickhouse-gh Bot added a commit that referenced this pull request Sep 17, 2026
Backport #116446 to 26.7: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
clickhouse-gh Bot added a commit that referenced this pull request Sep 17, 2026
Backport #116446 to 26.6: Do not use the distributed-plan Shuffle aggregation when bucket order is promised
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…huffle aggregation when bucket order is promised
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Sep 19, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

It reproduces, but not through the route #116446 closed, and not from your PR.

The abort on ea81c8ff is my own 04878_distributed_plan_shuffle_bucket_order_promise running under the stress runner's enable_cascades_optimizer = 1. From fatal.log: query_id ab1eae47-1975-404b-a1a4-2bdda9d9f088, log_comment = '04878_distributed_plan_shuffle_bucket_order_promise.sql-test_7', and the changed settings include make_distributed_plan = true, distributed_plan_force_shuffle_aggregation = true and enable_cascades_optimizer = true.

That last setting picks the planner: optimizeTree.cpp calls tryMakeDistributedAggregation only when enable_cascades_optimizer is off, and runs CascadesOptimizer instead when it is on. #116446 put the bucket-order guard inside tryMakeDistributedAggregation, so the guard is not on this path at all. On its own path it does override distributed_plan_force_shuffle_aggregation, so that setting being true here is not the explanation. The Cascades implementation rule in Cascades/Rules/AggregationImplementations.cpp has no bucket-order check on master.

The fix for the Cascades route is #119814, which is not mine: it adds that check, and pins enable_cascades_optimizer = 0 in 04878. Open since 2026-09-13, mergeable, no review yet.

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 6db2ead5, azure amd_tsan at 8601c8dd.

alexey-milovidov added a commit to zvonand/ClickHouse that referenced this pull request Sep 25, 2026
…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]>
@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

can be tested Allows running workflows for external contributors comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.

8 participants