Repository navigation
Conversation
…stributed aggregation GroupingAggregatedTransform may emit two-level buckets out of order (the optimization from ClickHouse#80179, enabled by default). Its sibling producer ConvertingAggregatedToChunksTransform records the still-pending buckets in the out_of_order_buckets metadata of each emitted chunk, but GroupingAggregatedTransform did not: pushData built a ChunksToMerge with no such field, and MergingAggregatedBucketTransform built a fresh AggregatedChunkInfo that dropped it. In a multi-layer distributed query (e.g. a Distributed table over Distributed tables, test 01223_dist_on_dist), a middle layer re-merges with num_merging_processors <= 1, so there is no SortingAggregatedTransform to re-sort its output. That layer can therefore emit an out-of-order bucket stream carrying no delayed-bucket metadata. The next layer's GroupingAggregatedTransform then has no "still owed" signal: its in-order push path finalizes a bucket with partial data and advances next_bucket_to_push past it; when the late copy of that bucket arrives it is pushed again. The duplicate is fanned by the downstream Resize to two SortingAggregatedTransform inputs, which throws "SortingAggregatedTransform already got bucket with number N" (a LOGICAL_ERROR, caught in release builds, aborting in debug/sanitizer/stress builds). This is why the failure appears only on multi-layer distributed queries under stress/sanitizer builds and never on a single node. Propagate the metadata through the re-merge path so the same contract holds at every layer: GroupingAggregatedTransform::pushData stamps every still-pending bucket (buffered in chunks_map, or flagged delayed by an input) except the one being pushed, and MergingAggregatedBucketTransform copies it into the output AggregatedChunkInfo. With the delayed-bucket signal present, the downstream in-order push path skips a bucket still owed and never pushes it twice. The out-of-order emission optimization is preserved. Add a unit test that drives the real GroupingAggregatedTransform through a faithful two-layer model (an inner transform per shard whose stamped metadata is forwarded as MergingAggregatedBucketTransform would, feeding the initiator); it reproduces the duplicate push without the fix and passes with it, alongside a 40k-iteration fuzz. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260628-004700 |
|
cc @nickitat @KochetovNicolai — could you review this? |
|
Workflow [PR], commit [b429c88] Summary: ❌
AI ReviewSummaryThis PR propagates Findings
Tests
Final Verdict
|
…rder_buckets Address review on the metadata-propagation fix: pushData stamped every out_of_order_buckets map entry that was absent from chunks_map, but the map keeps zero-count entries. An input can declare a bucket delayed, resolve it empty (so it is never buffered), and move on; that leaves a num_inputs_delaying == 0 entry. Forwarding it told the next distributed layer the input still owed that bucket, so real data for it from other inputs was buffered until the stream finished, breaking the memory-efficient merge contract. Stamp a delayed bucket only while its delaying count is positive (it is still owed by some input). Add a sparse/empty-bucket regression: a delayed-then-empty bucket must not be stamped as owed, and a downstream layer must still merge that bucket's real data from a sibling input instead of holding it to the end. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — 2660073Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
No ClickHouse test failures on this commit (149 checks pass, 0 test FAIL/ERROR in CIDB). The Session id: cron:our-pr-ci-monitor:20260629-020000 |
|
This PR awaits #108827 |
|
@groeneai Here is a reproduction. Let's add this to test. Need to run the following query 5-6 times to reproduce. -- Run this 5-6 times
CREATE TABLE t (k UInt64, v UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO t SELECT number % 100000, number FROM numbers_mt(3000000);
CREATE VIEW t_leaf AS SELECT if(cityHash64(queryID()) % 2 = 0, k, k % 4) AS k, v FROM t;
CREATE TABLE region AS remote('127.0.0.1,127.0.0.1', currentDatabase(), t_leaf);
-- enable_producing_buckets_out_of_order_in_aggregation = 1 (sometimes returns > 0 which is wrong)
SELECT count() - uniqExact(k) AS duplicate_groups
FROM (SELECT k, uniqExact(v) AS u FROM remote('127.0.0.1,127.0.0.1', currentDatabase(), region) GROUP BY k)
SETTINGS prefer_localhost_replica = 0, group_by_two_level_threshold = 1, max_threads = 16, enable_producing_buckets_out_of_order_in_aggregation = 1;
-- enable_producing_buckets_out_of_order_in_aggregation = 0
SELECT count() - uniqExact(k) AS duplicate_groups_with_workaround
FROM (SELECT k, uniqExact(v) AS u FROM remote('127.0.0.1,127.0.0.1', currentDatabase(), region) GROUP BY k)
SETTINGS prefer_localhost_replica = 0, group_by_two_level_threshold = 1, max_threads = 16, enable_producing_buckets_out_of_order_in_aggregation = 0; |
|
@nihalzp thanks for the repro. I reproduced it and measured it against this PR's branch:
So the current fix reduces the rate ~6x but does not fully close this multi-layer shape (initiator -> I'll investigate why the residual out-of-order path still double-produces here and extend the metadata propagation so your repro passes deterministically, then add it as the regression test in this PR. |
|
@nihalzp I traced the residual with per-transform instrumentation (debug build off this branch, the exact repro). It is one Why the guard passes early: the late-delivering input's carried The flicker is structural. I tried making the producer stamp monotonic (a bucket stays advertised until this transform resolves it, like So I did not add the repro as a |
|
Dear @nickitat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
| /// Carry the delayed-bucket signal through so a downstream GroupingAggregatedTransform | ||
| /// (e.g. in a multi-layer distributed query) still knows which out-of-order buckets are | ||
| /// still coming; otherwise it may push a bucket twice. | ||
| res_info->out_of_order_buckets = chunks_to_merge->out_of_order_buckets; |
There was a problem hiding this comment.
Copying the sender's out_of_order_buckets snapshot verbatim only fixes the num_merging_processors <= 1 re-merge. When this pipeline runs with more than one merge thread, the chunk still goes through SortingAggregatedTransform, which reorders buckets after the snapshot has been stamped while preserving out_of_order_buckets unchanged.
The next GroupingAggregatedTransform still treats that field as a per-input state diff in addChunk (decrement the previous snapshot, then increment the new one), so once the snapshots are replayed in a different order they no longer mean "buckets this input still owes right now". A delayed bucket can therefore disappear from the downstream count before the late contribution actually arrives, and that bucket can still be finalized with partial data.
The new fuzz does not close this gap because runRemoteShard() returns GroupingAggregatedTransform::runPushed() directly instead of routing the inner layer through the real ResizeProcessor / SortingAggregatedTransform branch. Please either re-derive the delayed-bucket metadata after sorting, or extend the regression to the actual multi-threaded path and fix the remaining mismatch there.
There was a problem hiding this comment.
Agreed on the mechanism, and it matches what I measured independently on this branch.
I instrumented this pipeline on 2026-07-22 and traced the same thing from the producer side: GroupingAggregatedTransform stamps each chunk with the buckets pending at emission time, then ResizeProcessor and SortingAggregatedTransform reorder those already-stamped chunks by bucket without recomputing anything (SortingAggregatedTransform::addChunk at cpp:462-485 only sorts and records last_bucket_number). Your paragraph 2 states the consumer half of the same defect: GroupingAggregatedTransform::addChunk treats the field as a per-input state diff at cpp:317-321 (decrement the previous snapshot, increment the new one), so replayed-out-of-order snapshots stop meaning "buckets this input still owes right now". Traced instance at the initiator: bucket 160 present on chunks 155-159, absent 161-170, back on 171-172, then delivered late. Full write-up: #108727 (comment)
Measured effect on this branch: the SortingAggregatedTransform already got bucket logical error is eliminated (0/30 runs), but the wrong-result residual persists at about 2-3/150 runs with enable_producing_buckets_out_of_order_in_aggregation = 1, and 0/20 with it set to 0. I tried making the producer stamp monotonic-until-resolved (a pending bucket stays advertised until that transform resolves it, mirroring ConvertingAggregatedToChunksTransform); it took the rate from about 11% down to about 2-3/150 but did not close it, so I did not ship it. Reducing a wrong-result rate is not a fix.
Your paragraph 3 is correct and it is the most useful part of the review. I checked runRemoteShard: it returns d.runPushed() (cpp:604) and the caller forwards that sequence in emission order (cpp:636-640), so the inner layer never traverses pipe.resize(num_merging_processors) plus SortingAggregatedTransform (cpp:598-606). The fuzz therefore models metadata propagation but not the reorder step, which is exactly where the residual lives. That is a real coverage gap in my own test and I will extend the inner layer to route through the actual multi-threaded branch.
One reachability detail worth recording: the reorder branch is not an exotic configuration for this shape. aggregation_should_produce_results_in_order_of_bucket_number is true whenever to_stage == WithMergeableState and distributed_aggregation_memory_efficient is on (Planner.cpp:480-482, the setting defaults to true), and num_merge_threads falls back to max_threads when aggregation_memory_efficient_merge_threads is 0 (its default). So any middle distributed layer with max_threads > 1 takes the SortingAggregatedTransform path, which is why the SQL repro on this PR still shows duplicate groups.
On your first suggested remedy, re-deriving the delayed-bucket metadata after sorting: I agree that is the correct layer, and it is the open question I put to the owner of the out-of-order optimization on the thread linked above, since it changes that machinery rather than this re-merge site. It is deferred pending that decision, not dismissed. The metadata-propagation fix in this PR stands on its own for the logical-error path, and I am not adding the SQL repro as a strict duplicate_groups = 0 assertion while the residual is nonzero, because that would land as a flaky test on this PR's own CI.
|
I'm trying to implement a complete fix in #112794 |
|
I read the diff of #112794. It subsumes this PR: it carries equivalent versions of both of my hunks (the So I am happy to close this PR in favour of #112794. Let me know if you want that, or if you would rather I keep it open for something. Two measurements from my branch that bear on your test, since it uses the same topology:
I also have a fuzz gtest for the |
…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
`Bugfix validation (unit tests)` builds the merge-base sources with only the pull request's unit-test files overlaid and requires the new test to FAIL at runtime there. `gtest_grouping_aggregated_transform_ooo.cpp` read `ChunksToMerge::out_of_order_buckets` - a field this pull request adds - so the "before" binary did not even compile, and the job reported the validation as inconclusive rather than as a reproduction: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108727&sha=1753e6cc0e2ad33c0c70abebb9334a2632e31f11&name_0=PR&name_1=Bugfix%20validation%20%28unit%20tests%29 ClickHouse#108727 Instead of reading the new field, the test now runs every chunk pushed by `GroupingAggregatedTransform` through a real `MergingAggregatedBucketTransform` - the processor that separates two `GroupingAggregatedTransform` layers in a multi-layer distributed query - and reads `AggregatedChunkInfo::out_of_order_buckets` from its output, which exists on both sides of the fix. That is also a better test: the two-layer cases now exercise the re-merge change itself instead of modelling it by copying the fields by hand. Because every pushed bucket now goes through a real aggregation merge, the two two-layer fuzz loops run 2000 iterations instead of 40000; both still reproduce the duplicate push on the very first iteration without the fix. Verified locally: with the fix all 15 `GroupingAggregatedOOO` cases pass (2.6 s); with `MergingAggregatedMemoryEfficientTransform.{h,cpp}` reverted to the merge-base the test compiles and `TwoLayerDistMetadataFuzz` and `TwoLayerDistSparseEmptyBucketFuzz` fail. Co-Authored-By: Claude Fable 5 <[email protected]>
Build (arm_tidy) failed with -warnings-as-errors:
gtest_grouping_aggregated_transform_ooo.cpp:152:39: error: 'chunk' used
after it was moved [bugprone-use-after-move,hicpp-invalid-access-moved]
note: the use happens in a later loop iteration than the move
reMergeBucketChunk drives the merger in a loop and delivers its chunk on the
first NeedData, so the move is guarded by a bool that clang-tidy cannot follow
across the loop back edge. The code was correct, but the check reports the
back edge, not a real second move.
Hold the chunk in a std::optional and reset it after delivery, so the
at-most-once property is structural instead of carried by a flag. Clearing the
chunk after the move does not help (clang-tidy then reports the clear() call
itself), and the chunk cannot be its own flag either: its header is empty, so
it is indistinguishable from a moved-from chunk.
Test only, no change in behaviour. The full clang-tidy check set is clean on
the file, the suite still passes 15/15 with the fix, and with
MergingAggregatedMemoryEfficientTransform.{h,cpp} reverted to the merge base it
still compiles and TwoLayerDistMetadataFuzz and TwoLayerDistSparseEmptyBucketFuzz
still fail, so the regression test keeps detecting the bug.
Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 407/409 (99.51%) · Uncovered code |
CI finish ledger - b429c88Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Notes. The previously reported Session id: cron:our-pr-ci-monitor:20260801-093000 |
|
Closing in favor of #112794 |
|
Agreed. #112794 is the complete fix and mine was not: the re-derivation in One thing dies with this PR and exists nowhere else: |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix the logical error
SortingAggregatedTransform already got bucket with number Nthat could occur in multi-layer distributedGROUP BYqueries (aDistributedtable overDistributedtables) using two-level aggregation.Description
GroupingAggregatedTransformmay emit two-level buckets out of order (the optimization from #80179, on by default). Its sibling producerConvertingAggregatedToChunksTransformrecords the still-pending buckets in each chunk'sout_of_order_bucketsmetadata, butGroupingAggregatedTransformdid not:pushDatabuilt aChunksToMergewithout that field, andMergingAggregatedBucketTransformbuilt a freshAggregatedChunkInfothat dropped it.In a multi-layer distributed query (e.g.
01223_dist_on_dist), a middle layer re-merges withnum_merging_processors <= 1, so there is noSortingAggregatedTransformto re-sort its output. That layer can emit an out-of-order bucket stream carrying no delayed-bucket metadata. The next layer'sGroupingAggregatedTransformthen has no "still owed" signal: its in-order push path finalizes a bucket with partial data and advancesnext_bucket_to_pushpast it; when the late copy arrives it is pushed again. The downstreamResizefans the duplicate to twoSortingAggregatedTransforminputs, which throwsalready got bucket(aLOGICAL_ERROR, caught in release, aborting in debug/sanitizer/stress builds). This is why it appears only on multi-layer distributed queries under stress/sanitizer builds and never on a single node.The fix propagates the metadata through the re-merge path so the same contract holds at every layer:
pushDatastamps every still-pending bucket (buffered inchunks_map, or flagged delayed by an input) except the one being pushed, andMergingAggregatedBucketTransformcopies it into the outputAggregatedChunkInfo. The out-of-order emission optimization is preserved. Theout_of_order_bucketsfield already exists inBlockInfo(gated byDBMS_MIN_REVISION_WITH_OUT_OF_ORDER_BUCKETS_IN_AGGREGATION), so there is no format or protocol change.A unit test drives the real
GroupingAggregatedTransformthrough a faithful two-layer model and reproduces the duplicate push without the fix, passing with it, alongside a 40k-iteration fuzz.Closes: #111441