Skip to content

Fix SortingAggregatedTransform "already got bucket" in multi-layer distributed aggregation - #108727

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-sorting-aggregated-already-got-bucket-multilayer-dist
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-sorting-aggregated-already-got-bucket-multilayer-dist

Conversation

@groeneai

@groeneai groeneai commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

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 the logical error SortingAggregatedTransform already got bucket with number N that could occur in multi-layer distributed GROUP BY queries (a Distributed table over Distributed tables) using two-level aggregation.

Description

GroupingAggregatedTransform may emit two-level buckets out of order (the optimization from #80179, on by default). Its sibling producer ConvertingAggregatedToChunksTransform records the still-pending buckets in each chunk's out_of_order_buckets metadata, but GroupingAggregatedTransform did not: pushData built a ChunksToMerge without that field, and MergingAggregatedBucketTransform built a fresh AggregatedChunkInfo that dropped it.

In a multi-layer distributed query (e.g. 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 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 arrives it is pushed again. The downstream Resize fans the duplicate to two SortingAggregatedTransform inputs, which throws already got bucket (a LOGICAL_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: 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. The out-of-order emission optimization is preserved. The out_of_order_buckets field already exists in BlockInfo (gated by DBMS_MIN_REVISION_WITH_OUT_OF_ORDER_BUCKETS_IN_AGGREGATION), so there is no format or protocol change.

A unit test drives the real GroupingAggregatedTransform through a faithful two-layer model and reproduces the duplicate push without the fix, passing with it, alongside a 40k-iteration fuzz.

Closes: #111441

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The unit test GroupingAggregatedOOO.TwoLayerDistMetadataFuzz (and the minimal input0=[1,2,0], input1=[0,1,2]) reproduces the double-push on demand.
b Root cause explained? Yes. GroupingAggregatedTransform emits buckets out of order (the #80179 optimization) but pushData/MergingAggregatedBucketTransform dropped the out_of_order_buckets metadata. A downstream re-merge layer then has no "still owed" signal, its in-order push path finalizes a bucket with partial data + advances next_bucket_to_push, the late copy arrives, the finish-drain re-pushes it -> duplicate -> Resize fans it to two SortingAggregatedTransform inputs -> already got bucket.
c Fix matches root cause? Yes. It propagates the missing metadata (the symmetric completion of the #80179 producer design), not a symptom guard. The consumer logic is unchanged.
d Test intent preserved / new tests added? Yes. New unit test reproduces the double-push at the production-code level via a faithful two-layer model; no existing test weakened.
e Both directions demonstrated? Yes. Reverting only the .cpp stamping makes TwoLayerDistMetadataFuzz fail (bucket pushed 2 times); with the fix all 12 tests pass (20k + 40k fuzz iters). End-to-end 01223_dist_on_dist passes on a debug binary built with the fix.
f Fix is general across code paths? Yes. The change is in the single producer (pushData) and the single re-merge transform, covering all callers of addMergingAggregatedMemoryEfficientTransform; not a per-call-site patch.
g Fix generalizes across inputs? Yes. The fuzz spans 2-4 inner and 2-4 outer inputs, 3-12 buckets, single-level + two-level mix. The metadata is bucket-id based, so it is datatype-agnostic (type wrappers N/A — the logic is on bucket numbers, not column types).
h Backward compatible? Yes. out_of_order_buckets already exists in BlockInfo (field 3, gated by DBMS_MIN_REVISION_WITH_OUT_OF_ORDER_BUCKETS_IN_AGGREGATION); this only populates it on a path that previously left it empty. No new setting, no format/protocol change.
i Invariants and contracts preserved? Yes. Upholds the documented contract (out-of-order emission is allowed only when accompanied by out_of_order_buckets metadata) and SortingAggregatedTransform's "at most one chunk per bucket per input". The stamp excludes the bucket being pushed, consistent with ConvertingAggregatedToChunksTransform's erase-before-stamp.

Session id: cron:clickhouse-worker-slot-0:20260628-004700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @KochetovNicolai — could you review this? GroupingAggregatedTransform emits buckets out of order (the optimization from #80179) but did not propagate the out_of_order_buckets metadata through pushData / MergingAggregatedBucketTransform, so a downstream re-merge layer in a multi-layer distributed query lost the delayed-bucket signal and could push a bucket twice, tripping SortingAggregatedTransform already got bucket. The fix stamps the still-pending buckets on the output, mirroring ConvertingAggregatedToChunksTransform; the out-of-order optimization is preserved.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b429c88]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR propagates out_of_order_buckets through the single-thread re-merge path and adds focused regression tests, but it still does not preserve correct delayed-bucket state once a middle distributed layer goes through ResizeProcessor plus SortingAggregatedTransform. Because the default multi-threaded branch still reorders already-stamped snapshots without re-deriving them, the multi-layer distributed GROUP BY contract is still violated, so this should not merge as a complete fix.

Findings
  • ❌ Blockers
    • [src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.cpp:414] The fix copies the producer's out_of_order_buckets snapshot verbatim into each merged chunk, but in the normal num_merging_processors > 1 path that snapshot is then reordered by SortingAggregatedTransform without being recomputed ([src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.cpp:582-606]). The next GroupingAggregatedTransform still diffs out_of_order_buckets as per-input chronological state, so once those snapshots are replayed in bucket order a delayed bucket can disappear from the downstream count before its late contribution arrives and be finalized with partial data. That leaves the multi-layer distributed aggregation contract broken: depending on the outer pipeline it can still produce duplicated groups or partial aggregates even if the original SortingAggregatedTransform already got bucket logical error becomes rarer. Suggested fix: re-derive the owed-bucket metadata after the reorder point, or otherwise guarantee that downstream inputs observe snapshots in the same order they were stamped.
Tests
  • ⚠️ [src/Processors/tests/gtest_grouping_aggregated_transform_ooo.cpp:663-720] runRemoteShard() still stops at runReMerged() and feeds the initiator directly from MergingAggregatedBucketTransform output, so the new TwoLayerDist* fuzzes never traverse the real ResizeProcessor / SortingAggregatedTransform branch that causes the remaining mismatch. A focused regression needs to route the inner layer through that actual multi-threaded path and fail if the delayed-bucket metadata changes after sorting.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • Preserve or re-derive delayed-bucket metadata across the ResizeProcessor / SortingAggregatedTransform branch, not only across the num_merging_processors <= 1 re-merge.
    • Add a regression that exercises that real multi-threaded inner-layer path; the current runRemoteShard() model is not sufficient proof for the PR's stated fix.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 28, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2660073

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

No ClickHouse test failures on this commit (149 checks pass, 0 test FAIL/ERROR in CIDB). The num_inputs_delaying > 0 stamping guard fix plus the 3 sparse-empty-bucket regression tests are green across all sanitizers.

Session id: cron:our-pr-ci-monitor:20260629-020000

@nickitat nickitat self-assigned this Jun 29, 2026
@nickitat

Copy link
Copy Markdown
Member

This PR awaits #108827

@nihalzp

nihalzp commented Jul 22, 2026

Copy link
Copy Markdown
Member

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

https://fiddle.clickhouse.com/3833ebc5-f659-4162-b8a3-369dc51011dc

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nihalzp thanks for the repro. I reproduced it and measured it against this PR's branch:

  • Unfixed master (2beb103): setting=1 gives duplicate_groups > 0 in ~65% of runs (10/15, max 2735); setting=0 always 0.
  • This PR (2660073, debug build, fix confirmed in the binary): the SortingAggregatedTransform already got bucket LOGICAL_ERROR is gone, but the correctness issue your repro targets still reproduces in ~11% of runs (11/100, max 1172). No exception is thrown, it is a wrong result. setting=0 is always 0.

So the current fix reduces the rate ~6x but does not fully close this multi-layer shape (initiator -> remote(region) -> region = remote(t_leaf) -> view over local t). Adding your repro as a strict duplicate_groups = 0 regression test would still fail this PR's own CI, so the fix looks incomplete for this exact scenario.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nihalzp I traced the residual with per-transform instrumentation (debug build off this branch, the exact repro). It is one GroupingAggregatedTransform pushing a bucket twice: it emits the bucket out of order once a single input's copy is present (out_of_order_buckets count 0 and min(last_bucket_number) >= bucket), then the late second copy arrives and it pushes again.

Why the guard passes early: the late-delivering input's carried out_of_order_buckets does not list the bucket as delayed at that moment. Tracing one bucket (160) at the initiator, its metadata flickers: present on the chunks for buckets 155-159, absent on 161-170, back on 171-172, then 160 is delivered late. So out_of_order_buckets[160] decrements to 0 and the early push fires.

The flicker is structural. GroupingAggregatedTransform stamps each chunk with the buckets pending at emission time; ResizeProcessor + SortingAggregatedTransform then reorder those already-stamped chunks by bucket without recomputing the metadata, so the downstream layer sees the stamps in bucket order, detached from the emission timeline, and a still-owed bucket can drop out of its running view. The merged part of this PR removes the already got bucket LOGICAL_ERROR reliably; this residual wrong result is inherent to how out_of_order_buckets is derived and preserved across GroupingAggregatedTransform -> ResizeProcessor -> SortingAggregatedTransform -> network.

I tried making the producer stamp monotonic (a bucket stays advertised until this transform resolves it, like ConvertingAggregatedToChunksTransform): it drops the rate from ~11% to ~2% on debug but does not close it, because the reorder-after-stamp still detaches the metadata from emission order.

So I did not add the repro as a duplicate_groups = 0 test: at ~2% it would land as a flaky test on this PR's own CI. @nickitat this is the #80179 machinery: would re-deriving out_of_order_buckets after the reorder step be the right layer, or keep this PR to the crash fix and track the wrong result separately? I have the full traces.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

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.

@nickitat nickitat self-assigned this Jul 31, 2026
/// 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;

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.

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.

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 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.

@nickitat

Copy link
Copy Markdown
Member

I'm trying to implement a complete fix in #112794

@groeneai

Copy link
Copy Markdown
Collaborator Author

I read the diff of #112794. It subsumes this PR: it carries equivalent versions of both of my hunks (the pushData stamp, the MergingAggregatedBucketTransform forwarding, and the ChunksToMerge::out_of_order_buckets field) and adds the piece I did not have, the re-derivation in SortingAggregatedTransform::tryPushChunk. I also checked the one hazard that cost me time here: a bucket announced as delayed and then resolved empty leaves a zero-count entry, and forwarding it tells the next layer an input still owes a bucket that will never come, holding real data for it until end of stream. Your getDelayedBucketsBefore excludes it on both sides (num_inputs_delayed_that_bucket > 0 and !buffered_chunks.empty()), where I only guarded the owed side.

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:

  • With the stamp and the forwarding but no SortingAggregatedTransform re-derivation, the already got bucket logical error was gone (0 of 30 runs), but duplicated keys persisted: 1 of 100 runs in one trial and 11 of 100 in another, against 10 of 15 fully unfixed, and 0 of 20 with enable_producing_buckets_out_of_order_in_aggregation = 0. That is independent evidence the remaining duplication comes from the reorder layer rather than the stamp.
  • Given those rates, the 10 iterations in 04604 are near-certain to catch a full revert, but would catch a regression of the re-derivation half alone only about 10% to 70% of the time. If you want that half pinned harder, more iterations or a unit-level check would do it.

I also have a fuzz gtest for the GroupingAggregatedTransform metadata contract in this PR (40000 randomized two-layer cases, deterministic). It does not currently cover the reorder path, because its inner layer returns the pushed sequence directly instead of going through resize plus SortingAggregatedTransform, so it would need that added before it is useful to your change. Happy to move it over if you want it.

nickitat added a commit that referenced this pull request 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
alexey-milovidov and others added 2 commits August 1, 2026 04:45
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 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: 407/409 (99.51%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b429c88

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Bugfix validation (unit tests) harness inconclusive, not a test result: the job reports Submodule state differs between the merge-base and the checkout (contrib/aws-c-http) and refuses to build the before-binary, so no test ran a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

Notes. The previously reported Build (arm_tidy) failure is gone at this commit (success), so the
use-after-move fix pushed for it is confirmed effective. Every other check is success or skipped:
174 check-runs, 0 queued or in progress, Finish Workflow success. The remaining failure is a
harness-side abstention and cannot be caused by this diff.

Session id: cron:our-pr-ci-monitor:20260801-093000

@nickitat

Copy link
Copy Markdown
Member

Closing in favor of #112794

@nickitat nickitat closed this Aug 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed. #112794 is the complete fix and mine was not: the re-derivation in SortingAggregatedTransform is the half that closes the duplicated keys, which my branch measured as still present without it.

One thing dies with this PR and exists nowhere else: src/Processors/tests/gtest_grouping_aggregated_transform_ooo.cpp, 15 cases pinning the GroupingAggregatedTransform delayed-bucket metadata contract, three of them randomized fuzzers over two-layer topologies. It is not on master and not in #112794. As written it only exercises the no-reorder path, so its inner layer would need routing through resize plus SortingAggregatedTransform before it is useful to your change. If you want it, say so and I will open it as a test-only PR after #112794 merges. Otherwise I will drop it and not raise it again.

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 pr-bugfix Pull request with bugfix, not backported by default

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)

4 participants