Skip to content

Cherry pick #116446 to 26.7: Do not use the distributed-plan Shuffle aggregation when bucket order is promised - #120638

Merged
PedroTadim merged 13 commits into
backport/26.7/116446from
cherrypick/26.7/116446
Sep 17, 2026
Merged

PedroTadim merged 13 commits into
backport/26.7/116446from
cherrypick/26.7/116446

Conversation

@robot-ch-test-poll2

Copy link
Copy Markdown
Contributor

Original pull-request #116446

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 12 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: #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]>
…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 #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]>
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
#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
#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
#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
#116259
…et-pushed-twice-3rd-path

Do not use the distributed-plan Shuffle aggregation when bucket order is promised
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants