Skip to content

Parallelize aggregation-in-order via key-hash reshuffle (aggregation_in_order_shuffle) - #110102

Open
alexey-milovidov wants to merge 148 commits into
masterfrom
aggregation-in-order-shuffle
Open

alexey-milovidov wants to merge 148 commits into
masterfrom
aggregation-in-order-shuffle

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 11, 2026 •

Copy link
Copy Markdown
Member

Description

optimize_aggregation_in_order is not enabled by default because it is often slower than the default hash aggregation. The reason is structural: for a multi-stream read the whole aggregation is funneled through a single FinishAggregatingInOrderTransform, so it runs on ~2–6 cores regardless of max_threads and is 8–16× slower than the default parallel hash path for high-cardinality GROUP BY (it does less total CPU work, but cannot parallelize it).

This PR adds an experimental setting aggregation_in_order_shuffle (default 0) that removes that funnel by repartitioning the sorted streams with a new scatter transform (BufferedShardByHashTransform):

read N sorted streams
  -> scatter each stream by hash(GROUP BY keys) into num_shards           (BufferedShardByHashTransform)
  -> per shard: MergingSortedTransform(N -> 1)      -- groups are disjoint by key
  -> per shard: streaming AggregatingInOrderTransform + FinalizeAggregatedTransform

Each shard aggregates a disjoint set of keys, so there is no cross-shard coordination and no single-threaded merge, while each shard still streams out completed key groups (bounded, O(1) memory). It is only used when the GROUP BY order is not relied upon downstream (!memoryBoundMergingWillBeUsed(), no bucket-order requirement, no LIMIT push-down), and the output is therefore not ordered by the keys.

Bounded memory without deadlocks: back-pressure with progress markers

The per-shard merges are selective consumers: a sorted merge cannot emit anything until it has a head row from every input, so plain back-pressure between the N scatters and the M merges can deadlock (scatter 1 blocks on the full port of shard A, merge A waits for stream 2's next row of shard A, which is behind rows of shard B, scatter 2 blocks on the full port of shard B, and merge B waits for stream 1).

Instead of buffering without bound, the scatters send progress markers: every stream is sorted, so the last row of the chunk a scatter has read is a lower bound for everything it can still send to any shard. A scatter sends that bound as a virtual row (the existing MergeTreeReadInfo mechanism, which MergingSortedAlgorithm compares like a real row but never outputs) to a shard that waits for it, when the shard got no rows from the chunk or the scatter cannot read further because another shard's queue is full. All merges break ties by input number, so they order rows by the same total order, and the bounds cannot form a waiting cycle (the argument is in the comment of BufferedShardByHashTransform).

So the scatter uses ordinary back-pressure: each shard has a queue of at most 16 pending pieces, and a new chunk is read only while every queue is shorter. Memory is bounded by a few chunks per stream, whatever the distribution of the keys, and skewed data only slows the query down. There is no buffer limit to configure and nothing to fail, and there are no restrictions on the aggregate states or column types that pass through the shuffle.

Verified: 105 shuffle-vs-ordinary comparisons on uniform keys, parts with a single key each, interleaved key runs, GROUP BY a, b over ORDER BY a (equal sort keys spread across shards), and string keys, at max_threads from 2 to 64, both with 16 pending pieces and with 1 (the tightest setting for the markers): no hangs, identical results.

Results (100M rows, 25M keys, max_threads = 48, median of 5, shared machine)

One part (streams read disjoint key ranges):

GROUP BY default in-order (funnel) shuffle
sum 0.28 s 3.24 s 1.47 s
uniqExact 0.39 s 4.40 s 1.47 s

96 overlapping parts:

GROUP BY default in-order (funnel) shuffle
sum 0.28 s 0.76 s 1.03 s
uniqExact 0.41 s 1.39 s 1.14 s

Skewed input (16 parts with a single key each, 16M rows): 0.35 s and 70 MiB peak memory (10× faster than with one pending piece per shard, with the same memory).

Known limitations (why it stays off by default)

  • When the streams read disjoint key ranges (e.g. one large part), the per-shard merges must emit keys in global order, so with bounded memory the streams are effectively consumed one after another. With disjoint streams the merge is not needed at all, so aggregating each stream separately would be the natural follow-up.
  • With many streams (one per part), the per-shard merges become wide (112-way above) and dominate the CPU time.
  • It scatters raw rows, so it gives no benefit for low/medium cardinality, where in-order is already fast.

It is also not used when a GROUP BY key contains a floating-point type, Dynamic or JSON: routing hashes the stored bits, but the in-order grouping compares values, so +0.0 and -0.0 would be split between shards.

EXPLAIN PIPELINE is also fixed to render the scatter/merge stage of the in-order pipeline (it was previously omitted).

Changelog category (leave one):

  • Experimental Feature

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

Added an experimental setting aggregation_in_order_shuffle that parallelizes optimize_aggregation_in_order by repartitioning the sorted input by the hash of the GROUP BY keys into independent shards, removing the single-threaded merge bottleneck while keeping the bounded memory of aggregation-in-order. For high-cardinality GROUP BY it is several times faster than the ordinary aggregation-in-order. Disabled by default.

Documentation entry for user-facing changes

  • Documentation is written (the new setting is documented in src/Core/Settings.cpp).

Workflow [PR]
Sync PR [sync-upstream/pr/110102]

🤖 Generated with Claude Code

alexey-milovidov and others added 3 commits July 11, 2026 14:22
Adds an experimental setting `aggregation_in_order_shuffle` (default off).

Problem: with `optimize_aggregation_in_order`, the multi-stream pipeline funnels
every partially-aggregated stream through a single `FinishAggregatingInOrderTransform`,
so the whole aggregation runs at ~2-6 of N cores and is 8-16x slower than the default
parallel hash path for high-cardinality GROUP BY (though it uses far less memory). That
single-threaded funnel is why the setting is not a good default.

This change, when the group-by order is not relied upon downstream
(`!memoryBoundMergingWillBeUsed()`, no bucket-order requirement, no LIMIT push-down),
reshuffles the sorted input by the hash of the GROUP BY keys instead of funneling:

  read N sorted streams
    -> scatter each stream by hash(keys) into num_shards (BufferedShardByHashTransform)
    -> per shard: MergingSortedTransform(N -> 1)   [groups are disjoint by key]
    -> per shard: streaming AggregatingInOrderTransform + FinalizeAggregatedTransform

Each shard aggregates a disjoint key set independently and streams out completed key
groups, so there is no cross-shard merge and no single-threaded funnel.

`BufferedShardByHashTransform` gains a `max_queue_length` parameter; this path uses 0
(unbounded) because a per-shard sorted merge is a selective consumer and bounded
back-pressure on the scatter can deadlock.

Status (experiment): correct (verified by order-independent checksums against the
default path); for high-cardinality GROUP BY it is ~2-3x faster than the current
in-order path and uses ~10x less memory than the default. Known limitations, kept
behind the off-by-default setting: it scatters raw rows so it regresses for low/medium
cardinality, and the scatter+sorted-merge can still deadlock for very low cardinality
(long key runs) in the pull-based executor. A fully deadlock-free all-cardinality
version needs a custom fused N->M shuffle-merge processor, or gating the optimization to
high cardinality.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The reshuffle-then-merge aggregation-in-order path (scatter each sorted stream by
hash(keys) -> per-group sorted merge -> streaming per-group aggregation) deadlocked,
because the M per-group merges share the N scatters, and a scatter that cannot serve
one lane blocks it from serving all lanes. Two concrete causes:

1. Back-pressure coupling: a slow/full lane made the shared scatter stop reading, which
   starved the other lanes; with selective (sorted-merge) consumers this closed into a
   cycle (merger A waits on scatter X, which is blocked pushing to merger B, which waits
   on scatter Y, ...).
2. Drain phase: on input EOF the scatter only finished its outputs once *all* per-shard
   queues were empty, so a shard whose queue drained early stayed open-but-empty and a
   sorted merge waited on that exhausted input forever. This hung deterministically for
   non-overlapping data, where each input stream only covers part of the key range.

Fix, in BufferedShardByHashTransform's unbounded mode (max_queue_length == 0, used by the
in-order shuffle path):
- Demand-driven scheduling: push to every lane that can take data first, and pull a new
  input chunk only to feed an output that is ready AND starving (empty queue). The shared
  scatter therefore never stalls on a slow lane (its data is simply buffered), so there is
  no cross-lane cycle; and read-ahead — hence memory — is bounded by how far the fastest
  consumer runs ahead of the slowest, instead of pulling the whole input into the queues.
- On input EOF, finish each output whose queue is already empty (per output), so mergers
  get EOF on exhausted inputs and never wait forever.

Result: 0 deadlocks over 120+ runs across all cardinalities, both overlapping and
non-overlapping parts, and thread counts 8..128. Correct (order-independent aggregates
match the default). For high-cardinality GROUP BY the shuffle is now 4-11x faster than the
current single-threaded in-order path while using the same O(1) memory (~0.8-2GB), and up
to ~28x less memory than the default hash path. It still scatters raw rows, so it regresses
for low/medium cardinality (where in-order is already fast); gating it to high cardinality
is left as a follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Add 04511_aggregation_in_order_shuffle: verifies the shuffled aggregation-in-order
  produces results identical to the default hash aggregation and to the ordinary
  aggregation-in-order (order-independent checksums), across full-key / monotonic-prefix /
  low-cardinality GROUP BY and several aggregate functions, and that the shuffle path is
  actually used.
- AggregatingStep::describePipeline: also describe the `scatter` group in the in-order
  branch, so EXPLAIN PIPELINE shows the BufferedShardByHashTransform / MergingSortedTransform
  stage of the shuffle (previously omitted).
- Use VectorWithMemoryTracking for the scatter output-port vector (style).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f6ddc0]

Summary: ✅


AI Review

Summary

PR #110102 adds experimental aggregation_in_order_shuffle: hash-partition sorted input, merge each shard, and aggregate the disjoint key sets independently. The current implementation uses bounded queues and virtual progress markers. Reviewed all 26 changed files at 0f6ddc08263567952002fa4c09de5a023c6c11d4 and all prior discussion. No remaining actionable findings; earlier byte-budget findings concern an implementation that has been removed.

Consumers of the new marker chunks were traced through IMergingTransformBase, which recognizes zero-row virtual chunks, and MergingSortedAlgorithm, which compares their boundaries and skips their synthetic rows. Its normalization handles constant, sparse, and replicated columns. Downstream AggregatingInOrderTransform and FinalizeAggregatedTransform receive real merged rows; downstream termination propagates through the merges to the scatters.

All eight focused stateless tests passed in the current-head Fast test report. Full CI is still in progress. No local build or test execution was performed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 11, 2026
alexey-milovidov and others added 3 commits July 11, 2026 23:22
Addresses the two blockers of the AI review on
#110102:

1. Unbounded read-ahead. In the demand-driven scatter, a slow/blocked
   per-shard sorted merge lets a `BufferedShardByHashTransform` keep
   pulling input into one shard's queue (e.g. long runs of a single set
   of `GROUP BY` keys), so the reshuffle was not actually bounded-memory.
   Add a new setting `aggregation_in_order_shuffle_max_buffered_bytes`
   (default 512 MiB): all scatters of the stage share one byte counter,
   and once the queued bytes exceed the budget the next pull fails the
   query with `TOO_MANY_ROWS_OR_BYTES` instead of buffering without
   limit. Refusing to pull is not an option here - a selective merge may
   need this scatter's EOF to make progress, so the only bounded-memory
   behavior that cannot deadlock is to fail.

2. `max_rows_to_group_by`. The per-shard streaming path
   (`executeOnBlockSmall` / `mergeOnBlockSmall`) never calls
   `Aggregator::checkLimits`. Note that the ordinary funnel path does
   not enforce this limit either: its `MergingAggregatedBucketTransform`
   merges each bucket via `Aggregator::mergeBlocks`, which also never
   calls `checkLimits` - aggregation-in-order simply keeps a bounded
   working set of keys, so the limit is never tripped. To keep this
   experimental optimization from changing the observable behavior of a
   query that sets the limit, do not use the shuffle when
   `max_rows_to_group_by` is set (fall back to the ordinary pipeline).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- 04511: pin `enable_parallel_replicas = 0` so the `EXPLAIN PIPELINE`
  check stays meaningful. Under parallel replicas the plan switches to
  memory-bound merging and the shuffle is not applied, which made the
  test fail (`BufferedShardByHashTransform` absent) in the
  `ParallelReplicas` CI configuration:
  https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110102&sha=0879e0c836d0ff8a19b33920c72b1f592989a4fc&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

- 04514: verify the shuffle is disabled when `max_rows_to_group_by` is
  set, and that the result is then identical to ordinary
  aggregation-in-order with the same limit. The limit does not throw on
  either path (aggregation-in-order keeps a bounded working set of keys,
  so `checkLimits` is never tripped), so the test asserts result parity
  rather than an exception.

- 04515: verify `aggregation_in_order_shuffle_max_buffered_bytes`. Parts
  with a single, long `GROUP BY`-key run each are the worst case: a
  per-shard sorted merge can proceed only after the other scatters reach
  EOF, so a scatter must read its whole part into one shard's queue while
  that shard's merge is blocked. Long runs (many chunks per part) make
  this buffering deterministically large, so a tiny budget fails the
  query with `TOO_MANY_ROWS_OR_BYTES`, while the default budget produces
  the same result as the default aggregation.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Fast test failed 04511_aggregation_in_order_shuffle and
04515_aggregation_in_order_shuffle_buffer_budget:
- 04511: the `EXPLAIN PIPELINE` presence check returned `0` (no
  `BufferedShardByHashTransform` in the plan).
- 04515: the query with `aggregation_in_order_shuffle_max_buffered_bytes = 1`
  succeeded instead of throwing `TOO_MANY_ROWS_OR_BYTES`.

Both have the same root cause. The shuffle is disabled when
`max_rows_to_group_by` is set (the shuffle path does not enforce that limit, so
the gate keeps the experimental path from changing the observable behavior of a
limited query - see 04514). The stateless-test profile (`tests/config/users.d/limits.yaml`)
sets `max_rows_to_group_by = 10G` in the default profile, so the shuffle was
disabled for the whole test: 04511 never planned the shuffle, and 04515 ran
through the ordinary funnel path (which has no buffer budget) and therefore
never tripped the budget.

Reset `max_rows_to_group_by` to `0` at the start of both tests so the shuffle is
actually exercised, overriding the profile default. 04514 is unaffected: it pins
a non-zero `max_rows_to_group_by` on purpose to assert that the shuffle is
disabled in that case.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110102&sha=b14a6c7beada157d860f4a8266ef2053709182de&name_0=PR&name_1=Fast%20test
PR: #110102

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Heads-up on a non-obvious consequence of the max_rows_to_group_by == 0 gate (the one that disables the shuffle so it never has to enforce the group-by limit).

While fixing the Fast test failures I found the shuffle was never planned in the stateless-test environment at all: tests/config/users.d/limits.yaml sets max_rows_to_group_by = 10G in the default profile (a deliberately-high value meant to exercise the limit-checking code without actually limiting anything), so the gate tripped for every query. Both 04511 and 04515 were passing through the ordinary funnel path rather than the shuffle. I fixed the tests by resetting SET max_rows_to_group_by = 0 at the top of each (dddcc80), so they now exercise the shuffle as intended.

The broader implication is a design call for you: as gated, aggregation_in_order_shuffle is silently disabled for any query that sets max_rows_to_group_by — including the common case of setting it as a safety guardrail with a large value. That means the optimization is off by default in most real setups that use the limit, and it gets no incidental coverage from the rest of the suite (only the three dedicated tests exercise it, and only because they now pin the limit to 0).

Since neither the shuffle path nor the funnel path actually enforces max_rows_to_group_by for aggregation-in-order (the funnel keeps a bounded working set and never calls Aggregator::checkLimits either), an alternative would be to drop the gate and document that the limit is not enforced for in-order aggregation regardless of the shuffle. Leaving the decision to you.

alexey-milovidov and others added 3 commits July 12, 2026 07:44
Addresses the AI review on PR #110102
(#110102): the
`aggregation_in_order_shuffle_max_buffered_bytes` budget was checked before
`input.pull` but only charged later in `enqueue`, so every
`BufferedShardByHashTransform` could admit one full input chunk past the cap
before anything threw, overshooting the budget by up to one chunk per scatter
on wide pipelines.

Charge the pulled chunk against the shared counter the moment it is pulled (and
release it when it is split and re-charged per shard), so the shared budget
always reflects the in-flight read-ahead of every scatter and admission
decisions cannot overshoot by a whole chunk. Also release the charge if the
transform finishes while still holding an un-split pending chunk, so a leftover
charge never makes sibling scatters trip the budget spuriously.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the AI review on PR #110102
(#110102): the shuffled
aggregation-in-order path wires an intermediate graph of
`num_streams * num_shards` (== `getNumStreams` * `max_threads`) scatter->merge
ports, the same fan-out `canUseShardedAggregation` bounds, but it did not apply
that path's `100'000` guard. On very wide pipelines (many streams on
high-thread machines) building that graph is itself a memory/time regression
before aggregation begins.

Gate `use_shuffle_in_order` on `getNumStreams * max_threads < 100'000` so such
queries fall back to the ordinary in-order funnel, mirroring the existing
sharded-aggregation guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…udget

The reshuffle budget for `aggregation_in_order_shuffle` was checked only on
the pre-pull value of the shared `total_buffered_bytes` counter: `prepare`
loaded the counter, pulled a chunk, and only afterwards charged it via
`chargePendingInput`. A chunk that itself pushed the stage past
`aggregation_in_order_shuffle_max_buffered_bytes` was therefore still admitted,
and the over-budget condition was only noticed on the *next* pull. If that
chunk was the last one before the input reached EOF (the budget is never
re-checked on the drain-and-finish path), or if several scatters passed the
same pre-check concurrently, the query could exceed the configured budget and
even finish without ever throwing `TOO_MANY_ROWS_OR_BYTES`.

Re-check the budget right after charging the pulled chunk, so the counter now
includes that chunk (and any in-flight charges from concurrent scatters sharing
the counter). This rejects the chunk that crosses the cap on the same admission
path - `work` throws before the chunk is split, so nothing over-budget is
buffered - covering the last-chunk-near-EOF and concurrent-scatter cases. The
existing pre-pull check is kept as a short-circuit so a scatter does not pull
another chunk once the shared budget is already exhausted.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 12, 2026 11:17
The shuffle buffer budget summed `Chunk::allocatedBytes()` per queued chunk.
`IColumn::scatter` can share one physical buffer across all shard chunks: the
canonical case is `LowCardinality`, where `ColumnLowCardinality::scatter` keeps
a single shared dictionary across the shards while `allocatedBytes()` still
counts that dictionary on every shard chunk. One split therefore inflated
`total_buffered_bytes` by up to `num_shards` times the dictionary size (and by
many times more once several such chunks are queued), so
`aggregation_in_order_shuffle_max_buffered_bytes` could throw
`TOO_MANY_ROWS_OR_BYTES` on perfectly safe queries.

Charge `Chunk::bytes()` (i.e. `IColumn::byteSize`) instead, which deliberately
excludes a shared `LowCardinality` dictionary (see `ColumnLowCardinality::byteSize`),
so the counter reflects the bytes the stage actually owns.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… input

A `LowCardinality` aggregation-in-order-shuffle query with a large shared
dictionary and a comfortable (64 MiB) buffer budget must not throw: the shared
dictionary is stage-owned memory counted once, not per scattered chunk. Before
the accounting fix this query threw `TOO_MANY_ROWS_OR_BYTES` spuriously because
the shared dictionary was counted on every queued chunk. The test also checks
result parity with ordinary aggregation-in-order and that a tiny budget still
fails, so the budget mechanism keeps working for `LowCardinality` input.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits July 12, 2026 12:26
…he shuffle budget

The `aggregation_in_order_shuffle` repartitioning stage bounds its read-ahead
with a shared byte budget. It was summed per queued shard chunk via
`Chunk::bytes()`. But `ColumnLowCardinality::scatter` keeps one dictionary
shared across all shard chunks, and `ColumnLowCardinality::byteSize` reports
zero for a shared dictionary, so the budget dropped the dictionary entirely:
every buffered block kept a multi-MiB dictionary alive that the counter never
saw, and `aggregation_in_order_shuffle_max_buffered_bytes` could be exceeded by
one dictionary per buffered block without tripping (an under-count of ~100x on
the canonical `LowCardinality` case). Switching from the earlier
`allocatedBytes()` accounting to `bytes()` had fixed the opposite bug - counting
the shared dictionary once per shard, inflating the counter up to `num_shards`
times - but over-corrected into this under-count.

Account per input block instead of per queued chunk: charge the whole pre-split
block once (via `Chunk::allocatedBytes()`, measured before `scatter` shares any
buffer) and release the charge only when the block's last shard chunk leaves a
queue. This counts every buffer, the dictionary included, exactly once per
buffered block and keeps it charged for as long as the block keeps it alive,
regardless of how `scatter` shares it across the shards.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tionary

Rework the `LowCardinality` buffer-budget regression test for the per-block
accounting. The pathological single-key parts now assert the query THROWS at a
64 MiB budget: each buffered block keeps a multi-MiB dictionary alive, so with
the dictionary counted once per block the buffered bytes far exceed 64 MiB. When
the shared dictionary was dropped from the budget only the ~16 MiB of index
columns were charged and this budget wrongly passed, so the assertion catches a
regression back to per-chunk `Chunk::bytes()` accounting. A well-distributed
`LowCardinality` table checks result parity with ordinary aggregation-in-order
and that counting the dictionary per block does not spuriously trip a safe query.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new test `04520_aggregation_in_order_shuffle_low_cardinality_budget`
generated ~2 GB of `LowCardinality(String)` data (8 single-key parts of
500000 rows plus a 1000000-row wide table), which is fine on release/debug
builds (~2 s) but exceeds the 180 s per-run limit of the sanitizer flaky
check (`amd_tsan`/`amd_msan`), where every memory access is instrumented.

The buffer-budget `THROW` queries allocate only up to the budget before
throwing, so the dominant cost was the inserts. Shrink the single-key table
to 8 parts of 16000 rows and the wide table to 40000 rows, and lower the
budget from 64 MiB to 16 MiB. The regression guard is preserved: each
buffered block still keeps the whole ~5 MiB dictionary alive, so with the
dictionary counted once per block the buffered bytes reach ~40 MiB and cross
the 16 MiB budget, while the reverted accounting that dropped the shared
dictionary would charge only the sub-megabyte index columns of the 128000
rows and wrongly pass. The `THROW` fires deterministically (verified across
`max_block_size` in {8192, 16384, 65536, 100000} and 10 repeats), the
`FORMAT Null` output and reference are unchanged, and the reduced test now
runs in ~0.37 s - on par with the sibling 04515 that already passes the
flaky check.

CI report (flaky check timeout):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110102&sha=86e8bbb6f51a20a7456d60210f3106e639d6173f&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
PR: #110102

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 5 commits July 12, 2026 15:58
The `aggregation_in_order_shuffle` buffer budget released a block's charge
in `dequeue`, i.e. the moment a shard chunk left the scatter's internal
queue. But `dequeue` is called right before pushing the chunk to an
`OutputPort`, where it stays resident in the port state (still consuming
memory) until the downstream per-shard merge pulls it - `OutputPort::hasData`
remains true until then. So the bytes were forgotten while the memory was
still held: a scatter could park a full block in each of its `num_shards`
output ports while the shared counter read far less than the memory actually
buffered, letting the stage exceed `aggregation_in_order_shuffle_max_buffered_bytes`
without ever throwing (worst on wide pipelines / blocks that hash entirely to
one shard).

Keep each block's charge alive until the merge pulls its chunk out of the
port. `dequeue` no longer releases the charge; the pushed chunk is recorded in
`port_resident_block[shard]`, and `reclaimPortResidentChunks` (called at the
top of `prepare`) releases it once the port no longer holds data (the merge
pulled it) or the output finished and discarded it. `work` releases the charge
too if the output closed between `prepare` and `work`. A chunk is thus counted
for exactly as long as it is buffered anywhere between the scatter and the
merge.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Long single-key runs with a large `max_block_size` keep most of the buffered
data as big chunks in flight between the scatter and the per-shard merge (in
the scatter's output ports) rather than in its internal queue. With the port-
resident chunks counted, the buffered bytes far exceed a 6 MiB
`aggregation_in_order_shuffle_max_buffered_bytes`, so the query must throw
`TOO_MANY_ROWS_OR_BYTES`. When the charge was released on `dequeue` (before the
merge pulled the chunk out of the port), the queue-only counter stayed under
6 MiB and this budget wrongly passed - so the test fails on the previous
accounting and passes now. `max_threads` and `max_block_size` are pinned in the
query so the buffering shape does not depend on the harness's random settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…r-shuffle

Resolved conflicts in src/Processors/QueryPlan/AggregatingStep.cpp against the
"Revert Explain analyze" commit 93ee2f3, which removed the AggregatingStage
enum, the getStepGroups/getStepGroupName overrides, and the Processors scatter
member this branch relied on:
- kept master's include set, plus Common/VectorWithMemoryTracking.h used by the
  shuffle branch;
- describePipeline prints finalizing (restored by the revert) and scatter
  (this branch) in reverse pipeline order;
- replaced AggregatingStage::Scatter / AggregatingStage::PartialAggregation
  with the plain collector group indices used after the revert (scatter = 3,
  in-order aggregation = 0);
- re-added the Processors scatter member to AggregatingStep.h, now owned by
  this branch since the revert removed it from master.
…er's EOF

`OutputPort::finish` only sets `IS_FINISHED`; it does not discard a chunk
parked in the port, and the downstream merge still sees and pulls that chunk
before observing EOF. The EOF drain path finished every output whose queue was
empty, so a port could be finished (or the processor could even return
`Finished`) while its last chunk was still parked:

- `reclaimPortResidentChunks` treated `IS_FINISHED` as "chunk gone" and
  released the block's charge from `total_buffered_bytes` while the bytes
  were still resident between the scatter and the merge (under-count), and
- returning `Finished` with a parked chunk left its charge in the shared
  counter forever, making sibling scatters trip
  `aggregation_in_order_shuffle_max_buffered_bytes` spuriously (leak).

Now the EOF drain finishes an output only when its queue is empty AND no chunk
of ours is parked in the port, and the processor does not return `Finished`
while any parked chunk remains: the merge's pull of the parked chunk re-runs
`prepare`, which releases the charge and then finishes the emptied port. With
that invariant, a parked chunk on a finished port can only mean the downstream
closed the port without pulling (cancellation, LIMIT); the chunk is unreachable
and its charge is released, since nothing can reclaim those bytes and keeping
them charged could only fail sibling scatters spuriously.
The 6 MiB budget assertion of
`04521_aggregation_in_order_shuffle_port_residency_budget` failed in every CI
run with randomized settings: the query succeeded where `TOO_MANY_ROWS_OR_BYTES`
was expected. A per-shard merge absorbs one chunk per input lane while it
initializes (that chunk leaves the port, so its charge is legitimately
released) and cannot pull more until every lane has data or EOF. With a
randomized `max_insert_threads` > 1 each INSERT splits into several parts of
roughly one chunk each, so almost the whole table escapes into the merges'
initialization and the buffered counter never crosses the budget. Randomized
range splitting (`merge_tree_read_split_ranges_into_intersecting_and_non_
intersecting_injection_probability`) and two-level in-order merging
(`read_in_order_two_level_merge_threshold` can randomize below the part count)
erode the guaranteed buffered floor the same way, one first chunk per
sub-stream.

Pin `max_insert_threads = 1`, the range-split injection probability, and the
two-level merge threshold, and grow the parts from 100000 to 150000 rows. Now
at least 8 * (150000 - 65536) rows ~ 10.8 MB is charged simultaneously by the
time the last scatter finishes reading - no matter how the threads interleave -
which crosses the 6 MiB budget deterministically. Verified 12/12 plain runs
and 9/9 runs under adversarial session settings (`max_insert_threads` 2/3/12,
session `max_block_size` 8192/32911/100000, injection probability 0.72,
two-level threshold 5).
…ts are finished

`BufferedShardByHashTransform::work` threw `TOO_MANY_ROWS_OR_BYTES` on
`budget_exceeded` unconditionally. But `prepare` sets `budget_exceeded` and
returns `Ready`, and between that `prepare` and `work` a downstream can finish
every output of this processor: a `LimitTransform` closes all of its upstream
inputs the moment it reaches its limit, and a cancellation does the same. Once
every output is finished the buffered data is needed by nobody, so throwing
here could fail a query (e.g. an outer `LIMIT 1`) that is actually completing
normally.

`work` now re-checks whether every output is already finished before throwing.
If so, it drops the pending chunk (releasing its budget charge) and returns;
the next `prepare` observes the finished outputs and finishes the processor
cleanly. When at least one output is still open the buffered data is genuinely
needed, so the over-budget error still stands - the budget guarantee is
preserved (verified: the sibling budget tests 04511/04514/04515/04520/04521
still trip the budget, since their outputs are open when it trips).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (f9d40591) with no conflicts, and fixed the Style check failure on aa1ae2f9 (6f117ca8). The cpp check now rejects plain standard containers under src/Processors/Transforms, so BufferedShardByHashTransform uses VectorWithMemoryTracking, DequeWithMemoryTracking and UnorderedMapWithMemoryTracking instead. BufferedShardByHashTransform.cpp, AggregatingStep.cpp and gtest_buffered_shard_by_hash_budget.cpp compile against the merged tree. No other check failed, and there are no unresolved review threads.

# Conflicts:
#	src/Processors/QueryPlan/AggregatingStep.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (ff3e3cdf). There was one conflict, in the include list of src/Processors/QueryPlan/AggregatingStep.cpp, and I kept the PR's #include <Core/SortCursor.h>. AggregatingStep.cpp passes a syntax check against the merged tree.

The only failure on 6f117ca8 was 05315_freeform_structure_search_query_limits in Fast test (arm_darwin): after KILL QUERY it got MEMORY_LIMIT_EXCEEDED instead of QUERY_WAS_CANCELLED. That test covers the Freeform structure search and does not touch aggregation-in-order.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110102&sha=latest&name_0=PR&name_1=Fast%20test%20(arm_darwin) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix for 05315_freeform_structure_search_query_limits is in progress yet; the test is mine (#123238), so I'm investigating the Fast test (arm_darwin) failure now and will follow up here with a separate fix PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #131525 (test only). The KILL case raced the query's own max_memory_usage = 2000000000: on that darwin runner no client could connect to the server for 8.4 s right after the poll, so the search failed on the limit before the KILL QUERY client got in. The test now sends the KILL only while the search's peak memory is between 10 MB and 1 GB, and repeats the attempt when the KILL did not reach the query. It is not caused by this PR: 1 failure in about 170K runs since the test was added.

alexey-milovidov and others added 2 commits November 15, 2026 16:02
# Conflicts:
#	src/Processors/QueryPlan/BuildQueryPipelineSettings.cpp
…n `AggregatingStep.cpp`

The previous merge of `master` left the header included twice, which `clang-tidy`
rejects with `readability-duplicate-include` in `Build (arm_tidy, 4/4)`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110102&sha=latest&name_0=PR&name_1=Build%20(arm_tidy%2C%204%2F4)
PR: #110102

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thank you. The 05315_freeform_structure_search_query_limits failure is covered by #131525, so nothing more is needed for it in this PR.

Merged master into the branch (15cf1eb7). There was one conflict, in BuildQueryPipelineSettings.cpp: master now calls getEffectiveMaxThreads(*from), and I kept the PR's two aggregation_in_order_shuffle settings after that call. I also fixed the Build (arm_tidy, 4/4) failure on ff3e3cdf (2890245d). The previous merge had left #include <Common/VectorWithMemoryTracking.h> twice in AggregatingStep.cpp, which fails readability-duplicate-include. AggregatingStep.cpp, BuildQueryPipelineSettings.cpp and BufferedShardByHashTransform.cpp compile against the merged tree. There are no unresolved review threads.

zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
… memory limit

The KILL case of `05315_freeform_structure_search_query_limits` lost a race against the query's own
`max_memory_usage = 2000000000` on `Fast test (arm_darwin)` (PR ClickHouse#110102): no client could connect to
the server for 8.4 s right after the poll saw the search under way, the search reached its limit and
threw `MEMORY_LIMIT_EXCEEDED`, and the KILL then landed on the query while it was freeing its
candidates.

The KILL is now the poll itself and matches only while `peak_memory_usage` is between 10 MB and 1 GB,
so a sent KILL is always seen by the search, and a late one matches nothing instead of racing the
limit. The peak, not `memory_usage`: the current usage of a query that failed on its limit falls back
through the window while it frees its candidates. An attempt in which the query ended before any KILL
could be sent says nothing about KILL and is repeated, at most 3 times. `kill_throw_if_noop = 0`
keeps the empty matches off stderr. The client output goes to a file and the client is bounded by
`timeout 60`, as in the review change `ba2c2d703b40` of ClickHouse#123238, which never reached master.

Related: ClickHouse#110102
Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits November 21, 2026 19:31
…kers

The per-shard sorted merges of shuffled aggregation-in-order are selective
consumers, so plain back-pressure between the scatters and the merges could
deadlock, and the scatter buffered without bound behind a byte budget that
failed the query with `TOO_MANY_ROWS_OR_BYTES` when exceeded.

Instead, a scatter now pulls a new chunk only after all pieces of the previous
one are pushed, and sends a virtual row with the sort key of the last row read
to a shard that waits for it, when the shard got no rows from the chunk or the
scatter is blocked on another shard. All merges order ties by input number, so
the bounds cannot form a waiting cycle. Memory is bounded by a few chunks per
scatter, and skewed data only slows the query down.

This removes `aggregation_in_order_shuffle_max_buffered_bytes`, the byte
accounting, and the restriction on aggregate states with a non-trivial
destructor and on `Dynamic` / `JSON` inputs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…skew test

With a single pending piece per shard, a scatter cannot read ahead while any
one merge is briefly behind, so all shards advance in lockstep and a descheduled
thread stalls the whole stage. Each shard now has a queue of up to 16 pieces.
A new chunk is read only while every queue is shorter, and a marker is still
sent only to a shard with an empty queue, so the deadlock argument holds. On
parts with a single key each, this is ten times faster than one piece, with the
same peak memory.

Remove the tests of the byte budget and of the gates that existed only for it
(aggregate states with heap memory, `Dynamic` and `JSON` inputs). Add
`05842_aggregation_in_order_shuffle_skew`: single-key parts under
`max_memory_usage`, equal sort keys spread across shards (`GROUP BY k, v % 7`
over `ORDER BY k`), interleaved key runs, and `uniqExact` / `groupArray` states.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 22, 2026 23:40
…zed block sizes

The query under `max_memory_usage = '100M'` failed in CI with
`MEMORY_LIMIT_EXCEEDED` at about 96 MiB. The repartitioning holds up to 16
blocks per stream, so its memory is proportional to the size of a block, and
the test left that to the randomized settings:

- With a randomized `index_granularity` (up to 65536) or `index_granularity_bytes`
  the blocks read in order are several times larger: the query takes 110 MB with
  `index_granularity = 65536` and 180 MB with `max_block_size = 93603`, against
  34 MB with the defaults.
- With a randomized `max_compress_block_size` (about 3 MB) the read buffers alone
  take about 200 MB, with or without the shuffle.

Pin `index_granularity`, `index_granularity_bytes`, `min_compress_block_size` and
`max_compress_block_size` in the table, and `max_block_size` in the query. The
query now takes 13..17 MB, and the limit still tells a few blocks per stream from
whole parts (about 50 MB each).

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110102&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted)
#110102

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI failure on 28a69d45 was the new test 05842_aggregation_in_order_shuffle_skew, which hit MEMORY_LIMIT_EXCEEDED at about 96 MiB under max_memory_usage = '100M' in all eight failing jobs. It is a test problem: the repartitioning holds up to 16 blocks per stream, so its memory is proportional to the block size, and the test left that to the randomized settings.

Measured locally on the same data (peak memory of the query):

settings peak
defaults 34 MB
index_granularity = 65536 110 MB
index_granularity = 65536, max_block_size = 93603 150–180 MB
max_compress_block_size ≈ 3 MB (read buffers, same without the shuffle) 180–200 MB
pinned, as in the fix 13–17 MB

Fixed in e4524fe: the table pins index_granularity, index_granularity_bytes, min_compress_block_size and max_compress_block_size, and the query pins max_block_size = 8192. The limit still tells a few blocks per stream from whole parts (about 50 MB each). The test passes locally with the adverse settings from the failed runs.

Also merged master (b497f16), without conflicts. No unresolved review threads.

… of the part storage

The test took 105-215 seconds in the flaky checks under sanitizers (2 seconds
in a release build) and exceeded the limit of 180 seconds in 7 runs. Its time
is in the number of rows, while what it checks is the amount of buffered data,
so the first data set now has ten times fewer rows that are wider (8 parts of
100000 rows and about 31 MB each instead of 1000000 rows and about 50 MB), and
the second one has four times fewer rows. The query under `max_memory_usage`
reads blocks of 1024 rows and takes about 30 MB, while buffering whole parts
would take more than 200 MB.

In `Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel)`
the same query hit `MEMORY_LIMIT_EXCEEDED` with the randomized
`min_bytes_for_full_part_storage = 536870912`: reading a packed part from an
object storage takes more memory for the read buffers, which is unrelated to
the repartitioning. The table now sets `min_bytes_for_full_part_storage = 0`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110102&sha=e4524fe542d3487d84e7dd4f7763b81987203049&name_0=PR
#110102

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All three failed jobs on e4524fe5 were the new test 05842_aggregation_in_order_shuffle_skew, for two reasons, both in the test. Fixed in 198421ab.

  • Timeout in the flaky checks. Under ASan and TSan the test took 105–215 seconds in every run (2 seconds in a release build), and 7 runs exceeded the 180-second limit. It was slow everywhere, not hanging. The first data set now has ten times fewer, wider rows (8 parts of 100000 rows, about 31 MB each), and the second has four times fewer rows. I have no sanitizer build here, so the speed-up under sanitizers is not measured; in a release build the test's CPU time roughly halved.
  • MEMORY_LIMIT_EXCEEDED in Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel). CI narrowed it down to the randomized min_bytes_for_full_part_storage = 536870912. It did not reproduce on a local disk, so the cause is my reading of the error (the failed allocation was a 1 MiB chunk): the read buffers of a packed part on object storage, not the repartitioning. The table now sets min_bytes_for_full_part_storage = 0.

The memory check still discriminates: the query under max_memory_usage = '100M' peaks at about 30 MB with blocks of 1024 rows (it also passes with a 50 MB limit), while buffering whole parts would need more than 200 MB. Results are identical across 10 local runs with varied max_threads and max_block_size.

CH Inc sync was also red on e4524fe5; I did not look into it, and it will re-run on the new commit. There are no unresolved review threads.

alexey-milovidov and others added 2 commits November 23, 2026 10:36
…t type

The test failed with `MEMORY_LIMIT_EXCEEDED` (about 96 MiB with `max_memory_usage = '100M'`) in the flaky checks
and the targeted runs. Compact parts are read by whole granules whatever the `max_block_size` is, and the part type
depends on the randomized `min_bytes_for_wide_part`. With `index_granularity = 8192` the blocks had 8192 rows
(about 2.5 MB) instead of 1024, and the repartitioning holds up to 16 blocks per stream: the query took 106 to
133 MiB on compact parts.

The table now has `index_granularity = 1024`, the same as the `max_block_size` of the query, so a block has 1024
rows with both part types. The test passes with half of the memory limit on wide and on compact parts.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110102&sha=198421ab1eb40563d4beb6fe38fd2e8e499a924f&name_0=PR
#110102

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All eight failed jobs on 198421ab were the new test 05842_aggregation_in_order_shuffle_skew hitting MEMORY_LIMIT_EXCEEDED at about 96 MiB under max_memory_usage = '100M'. It is a test problem, fixed in fed1077d.

Compact parts are read by whole granules whatever the max_block_size is, and the part type depends on the randomized min_bytes_for_wide_part. The previous commit made the rows wide, so each insert could become a compact part with 8192-row blocks (about 2.5 MB) instead of 1024-row ones, and the repartitioning holds up to 16 blocks per stream.

Peak memory of the query, measured locally with the settings of the failing CI runs:

table peak
wide parts, index_granularity = 8192 29–39 MiB
compact parts, index_granularity = 8192 106–133 MiB
compact parts, index_granularity = 1024 4–8 MiB

The table now has index_granularity = 1024, equal to the max_block_size of the query. The whole test passes locally on wide and on compact parts with the limit lowered to 50M, with four sets of settings taken from the failing runs. This was a release build in clickhouse-local; I did not run it under sanitizers or the thread fuzzer.

Also merged master (0f6ddc08), without conflicts. I did not rebuild after the merge: the only file of this PR that master touched is src/Core/Settings.cpp.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants