Repository navigation
Parallelize aggregation-in-order via key-hash reshuffle (aggregation_in_order_shuffle) - #110102
alexey-milovidov wants to merge 148 commits into
Conversation
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]>
|
Workflow [PR], commit [0f6ddc0] Summary: ✅
AI ReviewSummaryPR #110102 adds experimental Consumers of the new marker chunks were traced through 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 VerdictStatus: ✅ Approve |
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]>
|
Heads-up on a non-obvious consequence of the While fixing the Fast test failures I found the shuffle was never planned in the stateless-test environment at all: The broader implication is a design call for you: as gated, Since neither the shuffle path nor the funnel path actually enforces |
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]>
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]>
…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]>
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]>
|
🕵 Merged |
# Conflicts: # src/Processors/QueryPlan/AggregatingStep.cpp
|
🕵 Merged The only failure on @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. |
|
Acknowledged. No fix for |
|
The fix is in #131525 (test only). The KILL case raced the query's own |
# 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]>
|
🕵 @groeneai, thank you. The Merged |
# Conflicts: # src/Common/Arena.h
… 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]>
Fixes the `modernize-use-nodiscard` clang-tidy error in the `arm_tidy` build: https://s3.amazonaws.com/clickhouse-test-reports/PRs/110102/867c7c09539b73864c6265ccc07099330732eec7/pr/build_arm_tidy_1_4/build_clickhouse/build_clickhouse.log Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master has moved to version 26.12, and 26.11 no longer gets new settings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
…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]>
|
🕵 The only CI failure on Measured locally on the same data (peak memory of the query):
Fixed in e4524fe: the table pins Also merged |
… 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]>
|
🕵 All three failed jobs on
The memory check still discriminates: the query under
|
…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]>
|
🕵 All eight failed jobs on Compact parts are read by whole granules whatever the Peak memory of the query, measured locally with the settings of the failing CI runs:
The table now has Also merged |
Description
optimize_aggregation_in_orderis 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 singleFinishAggregatingInOrderTransform, so it runs on ~2–6 cores regardless ofmax_threadsand is 8–16× slower than the default parallel hash path for high-cardinalityGROUP BY(it does less total CPU work, but cannot parallelize it).This PR adds an experimental setting
aggregation_in_order_shuffle(default0) that removes that funnel by repartitioning the sorted streams with a new scatter transform (BufferedShardByHashTransform):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 BYorder is not relied upon downstream (!memoryBoundMergingWillBeUsed(), no bucket-order requirement, noLIMITpush-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
MergeTreeReadInfomechanism, whichMergingSortedAlgorithmcompares 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 ofBufferedShardByHashTransform).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, boverORDER BY a(equal sort keys spread across shards), and string keys, atmax_threadsfrom 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):
sumuniqExact96 overlapping parts:
sumuniqExactSkewed 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)
It is also not used when a
GROUP BYkey contains a floating-point type,DynamicorJSON: routing hashes the stored bits, but the in-order grouping compares values, so+0.0and-0.0would be split between shards.EXPLAIN PIPELINEis also fixed to render the scatter/merge stage of the in-order pipeline (it was previously omitted).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added an experimental setting
aggregation_in_order_shufflethat parallelizesoptimize_aggregation_in_orderby repartitioning the sorted input by the hash of theGROUP BYkeys into independent shards, removing the single-threaded merge bottleneck while keeping the bounded memory of aggregation-in-order. For high-cardinalityGROUP BYit is several times faster than the ordinary aggregation-in-order. Disabled by default.Documentation entry for user-facing changes
src/Core/Settings.cpp).Workflow [PR]
Sync PR [sync-upstream/pr/110102]
🤖 Generated with Claude Code