Skip to content

Fix duplicated keys in nested distributed aggregation with out of order buckets - #112794

Merged
nickitat merged 14 commits into
masterfrom
fix-out-of-order-buckets-in-nested-distributed-aggregation
Aug 17, 2026
Merged

nickitat merged 14 commits into
masterfrom
fix-out-of-order-buckets-in-nested-distributed-aggregation

Conversation

@nickitat

@nickitat nickitat commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

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):

Fixed the logical error SortingAggregatedTransform already got bucket with number N that could occur in multi-layer distributed GROUP BY queries using two-level aggregation.


Closes: #111441

Version info

  • Merged into: 26.8.1.1574 (included in 26.8 and later)
  • Backported to: 26.7.4.51, 26.6.5.47

…er buckets

`ConvertingAggregatedToChunksTransform` can produce two-level buckets out of
order and reports the still delayed buckets in `AggregatedChunkInfo::out_of_order_buckets`,
so that the consumer knows that it cannot finalize those buckets yet.

An intermediate node of a nested distributed query (a `Distributed` table over
`Distributed` tables) re-merges partially aggregated data and sends the result
further, but it did not maintain that contract:

- `GroupingAggregatedTransform::pushData` created a `ChunksToMerge` without the
  list of the buckets it is still owing, and `MergingAggregatedBucketTransform`
  created a fresh `AggregatedChunkInfo` which dropped that list;
- `SortingAggregatedTransform` merges its inputs by bucket id assuming they are
  sorted, so it can also emit a bucket after a bucket with a bigger id, and the
  list produced by `GroupingAggregatedTransform` is not accurate for its output.

As a result an intermediate node could send buckets out of order without telling
the next node about it. The next node finalized such a bucket, then received a
late chunk for it and pushed the same bucket for the second time, so the same
keys were returned twice. The same duplicate could also make the next
`SortingAggregatedTransform` throw `SortingAggregatedTransform already got
bucket with number N`.

Now every transform of the memory efficient merging pipeline reports the buckets
which still can be pushed after the current one, so the contract holds on every
layer of a nested distributed query.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3e5623a]

Summary: ✅


AI Review

Summary

This PR propagates delayed-bucket metadata through the memory-efficient aggregation pipeline so nested distributed and parallel-replica merges do not finalize a bucket before all lower delayed buckets are accounted for. I did not find a remaining correctness issue in the current code, but the PR metadata still uses the wrong changelog category.

PR Metadata
  • Changelog category should be Bug Fix (user-visible misbehavior in an official stable release), not Critical Bug Fix (crash, data loss, RBAC): this is a user-visible wrong-results / logical-exception fix, but it is not a crash, data-loss, or RBAC issue.
  • Changelog entry is required for Bug Fix, and the current entry is specific enough as-is.
Missing context / blind spots
  • ⚠️ The only current Praktika artifact I could fetch from the PR discussion was Build profile diff; I did not have a current stateless or stress report for the new regression tests. A fresh functional CI run on the PR head would close that gap.
Final Verdict

✅ No actionable code findings in the current diff. Change the Changelog category to Bug Fix before merge; otherwise this looks ready.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.90% 78.90% +0.00%

Changed lines: Changed C/C++ lines covered: 68/76 (89.47%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Jul 31, 2026
…t merging pipeline

The stateless test is racy: it only detects the bug when the machine happens to
produce the right interleaving. These tests drive the transforms directly, so
the schedule is chosen rather than observed.

The tests for `GroupingAggregatedTransform` are taken from #108727. They model an
intermediate node as `GroupingAggregatedTransform` alone, which is only a half of
it: when `aggregation_memory_efficient_merge_threads` is greater than one (by
default it is `max_threads`), `addMergingAggregatedMemoryEfficientTransform`
builds

    GroupingAggregated -> Resize -> N x MergingAggregatedBucket -> SortingAggregated

and the mergers run concurrently, so `SortingAggregatedTransform` can emit a
bucket after a bigger one which `GroupingAggregatedTransform` emitted earlier.
Nothing stamped upstream describes such an inversion, which is why the metadata
has to be re-derived there instead of being forwarded.

`ManualSortingDriver` drives `SortingAggregatedTransform` through its ports with
a randomized merger completion order, and the new tests check the contract every
layer owes to the next one: a bucket emitted after a bigger one must have been
announced as delayed by that bigger one.

With the re-derivation in `SortingAggregatedTransform::tryPushChunk` reverted,
`SortingLayerRederivesDelayedBucketsFuzz` and
`TwoLayerDistThroughSortingLayerFuzz` fail while the rest of the file still
passes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
nickitat and others added 2 commits July 31, 2026 22:19
The assertion added with the fix required a strictly increasing bucket id from
each input, but the contract is non-decreasing: a single input can be a sequence
of several independent aggregation results, so it can send several chunks with
the same bucket id. This is exactly why `chunks_map` keeps `Chunks` per bucket
and not a single chunk. `02521_aggregation_by_partitions` hits it with
`force_aggregate_partitions_independently = 1`, where every partition is
aggregated on its own.

Repeating a bucket id is safe: a bucket is pushed only when `current_bucket` is
past it, which requires every input to have reported a bucket with a strictly
bigger id, so a repeated bucket can never arrive for an already pushed one.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112794&sha=abdd10d2a63f041a8c9246f944740c71d17377c1&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20parallel)
Related: #112794

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
The assertion does not hold for every pipeline. `MergingAggregatedTransform`
(used unconditionally by parallel replicas, `applyParallelReplicas` passes
`memory_efficient_aggregation = false`) emits the result of
`Aggregator::convertToChunks`, and `prepareChunksAndFillTwoLevelImpl` converts
the buckets with a thread pool where every thread appends to its own list, and
the per thread lists are spliced together at the end. So the emitted sequence is
a sawtooth: a thread that took most of the buckets is followed by a thread that
took a few small ones, e.g. bucket 254 is followed by bucket 2. When such a node
sends the result to a node which merges memory efficiently, the buckets arrive
out of order and nothing is reported as delayed. That is the same class of a
problem, but a different producer, and it is not touched by this change, so the
assertion only turns it into an exception in the debug builds.

Two unit tests, `OutOfOrderEmptyMetadataDoublePush` and
`OutOfOrderEmptyMetadataManyBackwardSteps`, also feed exactly such a stream on
purpose, and they aborted in the builds with assertions enabled.

The stateless test is made lighter, because it did not fit into the time limit
in the debug and sanitizer builds: 500000 rows instead of 3000000, `sum` instead
of `uniqExact` in the merged aggregation, and 8 repetitions instead of 10. Each
repetition reproduces the bug in about a half of the runs, so 8 of them are
enough. The queries now take 0.68 sec instead of about 3 sec.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112794&sha=435b36627330f14f7eaf5ac08149c3c35d297f01&name_0=PR
Related: #112794

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
nickitat and others added 3 commits August 1, 2026 12:19
…enabled

`applyParallelReplicas` created the `MergingAggregatedStep` which merges the
partially aggregated data of the replicas with a hardcoded
`memory_efficient_aggregation = false`, while the path it replaced,
`Planner::addMergingAggregatedStep`, obeys `distributed_aggregation_memory_efficient`
and lists `parallel_replicas_from_merge_tree` among the cases where it applies.

It is not only about the memory. The ordinary `MergingAggregatedTransform` reads
all the buckets before it returns anything, and it returns them in the order
produced by `Aggregator::convertToChunks`, where the buckets of a two level
result are converted by a thread pool, every thread collects the buckets it took
into its own list, and the lists are spliced together at the end. So the buckets
come out in an arbitrary order.

A shard of a `Distributed` table can read its local table with parallel replicas
(`ClusterProxy::executeQuery` keeps it enabled for the shards of a cluster which
has more than one replica per shard), and then it sends the merged result to the
initiator, which merges it memory efficiently. Buckets arriving out of order
there make the initiator merge and output the same bucket twice, and the result
contains duplicated keys. With a `Distributed` table over
`test_cluster_two_shard_three_replicas_localhost` and 200000 keys it reproduced
in 8 runs out of 8, with about 30000 duplicated keys each time.

Memory efficient merging is not supported for grouping sets, so it stays
disabled for them.

Also assert in `GroupingAggregatedTransform` that a bucket is never pushed twice.
That is the failure mode of every producer which sends the buckets out of order
without reporting them as delayed, and it is what both of the fixed bugs look
like from the consumer side.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
DO NOT MERGE THIS COMMIT. It is a copy of `ReadFromRemote.cpp` from the branch
`fix-parallel-replicas-duplicate-keys` (commit 56a18a4, "Do not read from
every replica of a shard when parallel replicas are not applicable"), added here
only to check that this branch becomes green once that fix is merged into master.

Without it every replica of a shard returns all of its data when parallel
replicas are not applicable, which multiplies the result of the shard and makes
the initiator receive several complete sequences of two-level buckets on a single
input port. That is what made `04605_parallel_replicas_merging_aggregated_bucket_order`
fail and the assertion in `GroupingAggregatedTransform` fire in the previous runs
of this branch, and it is not caused by the changes here.

Drop this commit before merging.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.50% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 563/568 (99.12%) · Uncovered code

Full report · Diff report

@nickitat

nickitat commented Aug 3, 2026

Copy link
Copy Markdown
Member Author

Couple of other issues were discovered in CI, fixing them there: #112942

nickitat and others added 3 commits August 3, 2026 11:27
… lose

`GroupingAggregatedTransform` stamps every `ChunksToMerge` it pushes with the ids
of the buckets it still owes, so that the node which merges the result does not
finalize such a bucket before its data arrives. `FlattenChunksToMergeTransform`
drops that wrapper and emits the chunks it holds, so the stamp is lost.

Today nothing is lost, because that transform is used only over
`ConvertingAggregatedToChunksSource`, which produces the buckets in order of their
id-s and never delays any of them, so the transform above always has an empty set
to stamp. It is not obvious from the code of the transform itself, hence the
assertion: if a producer which delays buckets is ever put there, the chunks have
to be stamped with `chunks_to_merge->out_of_order_buckets` instead.

Checked over 775 tests of the aggregation, partition, group by, distributed and
parallel replicas suites, including `02521_aggregation_by_partitions`, which is
the test that goes through this path: the set is always empty.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
The comments came with the tests and describe the behaviour before the fix:
they say that `MergingAggregatedBucketTransform` builds a fresh
`AggregatedChunkInfo` which does not copy `out_of_order_buckets`, and that an
empty set of delayed buckets is what a dist layer produces. It copies the set
now, so an empty set means that the producer reports no delayed buckets.

The tests themselves are left as they are: feeding a stream which is out of
order and reports nothing is still worth checking, it is what a producer which
does not maintain that metadata emits.

Also drop the references to the line numbers of other files, they were already
pointing at the wrong lines.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
…rival order

Of the 18 tests only 4 detected anything: reverting the stamping in
`GroupingAggregatedTransform::pushData`, the re-derivation in
`SortingAggregatedTransform::tryPushChunk` or the buffered buckets term of
`getDelayedBucketsBefore` failed the same few fuzz tests every time, the rest
passed under every one of those mutations. They are single points which the fuzz
tests sweep anyway, so they are removed, together with the pages of prose.

`ManualGroupingDriver` used to deliver from the first input which needs data, so
only what every input sends was fuzzed, never the order in which the inputs
arrive. Now it picks a random one of the inputs which can accept a chunk, like
`ManualSortingDriver` already does for the mergers.

What is left is the two drivers, the producer models, four fuzz tests and two
minimal cases which are worth reading: the smallest inversion the merging layer
creates on its own, and the bucket which is declared delayed and then resolved
empty.

Every one of the three mutations above is still caught, by 4, 2 and 4 of the 6
tests. 1122 lines -> 817, 5.7 sec -> 5.0 sec.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
nickitat and others added 2 commits August 7, 2026 14:37
`Aggregator::Params` got `enable_packed_string_keys_` in master, and the
merge brought it to the branch, so the test does not compile any more.
Pass the default value of the field, the test aggregates by a single
`UInt64` key and does not depend on it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 3e5623a - the build was skipped, reused from cache, or predates profile upload.

@nickitat
nickitat marked this pull request as ready for review August 10, 2026 10:36
@nickitat
nickitat added this pull request to the merge queue Aug 17, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Aug 17, 2026
@nickitat
nickitat added this pull request to the merge queue Aug 17, 2026
Merged via the queue into master with commit b159e61 Aug 17, 2026
355 of 356 checks passed
@nickitat
nickitat deleted the fix-out-of-order-buckets-in-nested-distributed-aggregation branch August 17, 2026 19:59
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 17, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 17, 2026
Backport #112794 to 26.7: Fix duplicated keys in nested distributed aggregation with out of order buckets
@PedroTadim

Copy link
Copy Markdown
Member

@nickitat

nickitat commented Aug 19, 2026 •

Copy link
Copy Markdown
Member Author

@nickitat @nihalzp it seems these CI failures from today s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115264&sha=c67596ccb46be3235cf51751deaa6a7206cd445b&name_0=PR&name_1=Stress+test+%28amd_debug%29 are caused by this PR

thanks, i will take a look
UPD: fix in #115487

@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 Aug 28, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 4, 2026
Backport #112794 to 26.6: Fix duplicated keys in nested distributed aggregation with out of order buckets
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
…tributed aggregation with out of order buckets
PedroTadim pushed a commit that referenced this pull request Sep 29, 2026
The robot cherry-pick of #112942 into 26.7 (#113810) came out conflicting and
was auto-closed after seven idle days without anyone resolving it. Eight hours
later the 26.7 backport of #112794 landed the "Bucket N is pushed twice"
assert and test 04605 on the branch, so 26.7 now asserts an invariant whose
fix it never received.

#112942 makes the per-shard replica merge that `applyParallelReplicas`
inserts obey `distributed_aggregation_memory_efficient`. Without it that merge
always takes the `!memory_efficient_aggregation` branch of
`MergingAggregatedStep::transformPipeline`, which resizes the pipeline to one
stream and uses the plain `MergingAggregatedTransform`. That transform emits
two-level buckets in `Aggregator::convertToChunks` order and never consults
`should_produce_results_in_order_of_bucket_number`, so a shard that promised
the initiator ascending bucket order breaks its own promise. The initiator's
memory-efficient merge then trips
`chassert(bucket < 0 || pushed_buckets.insert(bucket).second)` in debug and
sanitizer builds, and returns duplicated aggregation keys in release builds.

Merging `backport/26.7/112942` into `cherrypick/26.7/112942` conflicts in one
file, `applyParallelReplicas.cpp`, in one six-line region: master passes the
new `settings` argument to the visitor and calls
`insertParallelReplicasSplit(query_plan, nodes)` before it, a function added
to master after 26.7 was cut. The resolution keeps the `settings` argument and
drops the `insertParallelReplicasSplit` call.

The resolved file is byte-identical to master's own copy at the fix commit
7a902ae (blob 74365cc), because 26.7's
copy equals master's copy at that commit's parent. The resolution therefore
diverges from upstream by zero bytes. The other four source files and all
three new tests auto-merge clean.

(cherry picked from commit 0793ca6)
@blau-ai blau-ai mentioned this pull request Oct 8, 2026
20 of 30 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stress test: Logical error: SortingAggregatedTransform already got bucket with number A (STID: 3869-3f96)

6 participants