Repository navigation
Add GradualResizeProcessor to limit effective parallelism for GROUP BY on small data volumes - #99495
alexey-milovidov wants to merge 211 commits into
Conversation
When ClickHouse processes GROUP BY, it often overestimates the number of threads needed. With `max_threads = 64` but only a few thousand rows, all 64 `AggregatingTransform` instances get data, produce 64 partial hash tables, and the merge phase has to combine all of them — most nearly empty. This wastes time on merging overhead. The new `GradualResizeProcessor` starts by pushing data to only 1 output port, and gradually activates more ports as data volume grows. For small datasets, only 1-2 aggregating threads receive data; for large datasets, all threads are used as before. New settings (both default to 0 = disabled): - `min_rows_per_stream_for_gradual_resize` - `min_bytes_per_stream_for_gradual_resize` When either threshold is non-zero, the pre-aggregation `StrictResize` is replaced with `GradualResize` in the pipeline. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [65b53a2] Summary: ✅
AI ReviewSummaryThis PR adds the opt-in Final Verdict✅ Approve. LLVM Coverage ReportMeasured on commit 65b53a2.
Changed lines: Changed C/C++ lines covered: 372/383 (97.13%) · Uncovered code |
ClickBench Q36-Q42 benchmarks show 1.11x geometric mean speedup with `min_rows_per_stream_for_gradual_resize = 1000`: - Q40 (426K-group filtered aggregate): 40ms → 29ms (1.38x) - Q38 (42K groups): 18ms → 14ms (1.29x) - Q37 (299K groups): 22ms → 19ms (1.16x) - Q36 (full-table 9.1M groups): 36ms → 38ms (5% regression, acceptable) - Q39, Q41, Q42 (very selective): neutral Higher thresholds (50K+ rows) cause regressions on large datasets by keeping parallelism too low for too long. 1000 rows/stream is the sweet spot: conservative enough to ramp up quickly for heavy queries, but effective at reducing merge overhead for filtered aggregates. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Skip finished outputs when dequeuing from `active_waiting_outputs` and when promoting entries from `inactive_waiting_outputs`. Without these guards, a downstream cancellation could mark an output as `Finished` while it was still enqueued, leading to an invalid `pushData` call. Also disable `min_rows_per_stream_for_gradual_resize` in three existing tests that validate pipeline structure or thread-count assumptions unrelated to gradual resize. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Fix stateless test `04039_gradual_resize_processor`: set `enable_analyzer = 1` at session level so the test works in old-analyzer CI configurations - Fix `test_storage_mysql::test_many_connections`: disable `GradualResize` for this test because 25 UNION ALL branches with a MySQL connection pool of 16 causes pool exhaustion — `GradualResize` bottlenecks data through 1 output initially, so MySQL sources hold connections longer and waiting sources time out Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…x performance regressions The original `GradualResizeProcessor` replaced `StrictResizeProcessor` in the aggregation pipeline but used non-strict FIFO routing — any input could feed any output. This destroyed thread/cache locality and caused regressions on large datasets: - `group_array_sorted`: up to +146% slower on AMD, +39% on ARM - `sort_patterns #4`: +408% on ARM - `optimize_functions_to_subcolumns`: +15-50% on AMD Root cause: even after all outputs activated (which happens after the first 65K-row chunk with threshold=1000), data was routed arbitrarily instead of maintaining the 1:1 input-output binding that `StrictResizeProcessor` provides. Fix: rewrite `GradualResizeProcessor` to use strict routing (like `StrictResizeProcessor`). Inputs start disabled and are only enabled when bound to a specific active output. This preserves thread locality for large datasets while still providing the gradual activation benefit for small GROUP BY queries. Performance report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99495&sha=edb0902ed32ccbbf461112a71a027e24b1cdfcd2&name_0=PR Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
In this PR, we try to gradually increase the active input and output ports as incoming data reaches our processor and crosses some threshold. The issue with this is that this can lead stalling in the upstream as well (as discovered by the performance tests). This happens because since at the start most of the input ports (except the first one) has not set One idea could be that we keep all the input ports and gradually allow output ports. We try to push the input chunk to any of the available allowed output chunks; in this way this will not linearize the pipeline while keeping most of the benefit. |
I actually meant it this way. Will try... |
…ually activate outputs Address review feedback from #99495: - Keep all input ports active at all times to avoid upstream pipeline stalling. Previously, inputs were disabled by default and bound 1:1 to outputs, which caused upstream transforms (e.g. `FilterTransform`) to stall when most inputs were inactive. Now uses many-to-many routing (like `ResizeProcessor`) with all inputs always active, while only gradually activating output ports as data volume grows. - Fix potential integer overflow in `maybeActivateMoreOutputs` by using division-based comparison instead of multiplication (`total_rows / num_active >= threshold`). - Remove `.claude/learnings.md` artifact file that was accidentally included. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ually activate outputs Address review feedback from #99495: - Keep all input ports active at all times to avoid upstream pipeline stalling. Previously, inputs were disabled by default and bound 1:1 to outputs, which caused upstream transforms (e.g. `FilterTransform`) to stall when most inputs were inactive. Now uses many-to-many routing (like `ResizeProcessor`) with all inputs always active, while only gradually activating output ports as data volume grows. - Fix potential integer overflow in `maybeActivateMoreOutputs` by using division-based comparison instead of multiplication (`total_rows / num_active >= threshold`). - Remove `.claude/learnings.md` artifact file that was accidentally included. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ke `StrictResizeProcessor` The original implementation enabled all inputs unconditionally, used decoupled queues for routing, and called `getNumRows`/`bytes` on every chunk even after all outputs were activated. This caused measurable steady-state overhead vs `StrictResizeProcessor`, leading to performance regressions in CI perf tests. The new implementation adopts `StrictResizeProcessor`'s pattern: - Each input is paired 1:1 with an output via `waiting_output` - Inputs are disabled after delivering data (`pullData(set_not_needed=true)`) - Inputs are only re-enabled when an output needs data (demand-driven) - Per-chunk row/byte accounting is skipped once all outputs are active (`all_outputs_active` flag) Once all outputs are activated, the processor behaves identically to `StrictResizeProcessor` with zero additional overhead. CI perf report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99495&sha=edb0902ed32ccbbf461112a71a027e24b1cdfcd2&name_0=PR Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…mplementation Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…stributed source in the decorrelation The decorrelation rebuilds the user's `AggregatingStep` with `storage_has_evenly_distributed_read = false` (its input is the decorrelating join, not the original storage), so the rebuilt copy reaches the pre-aggregation resize branch even when the original step skipped it. Carrying `enableGradualResize` over unconditionally therefore built a `GradualResize` for a correlated `GROUP BY` over `Memory` / `numbers_mt`, which the settings are documented to ignore, and which the same `GROUP BY` never builds on its own. Gate the carried bit on the original step's evenly-distributed-read property, exactly like the plan serialization already does for the shipped fragments; the rebuilt copy then keeps the strict resize it builds today. `AggregatingStep` exposes `storageHasEvenlyDistributedRead` for that. Test `05234` gains a `Memory` inner source: neither the plain `GROUP BY` nor its decorrelated copy may build a `GradualResize`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ed halfway
A processor that returns `Status::UpdatePipeline` connects its ports to the
new processors before `ExecutingGraph::updatePipeline` records them, and
recording them allocates (`processors->push_back`, `nodes.emplace_back`,
`processors_map.emplace`, the edge lists), so it can throw on the memory
limit halfway. The graph is then inconsistent with the ports: a live node
is connected to a processor that never became a node. The exception cancels
the executor, but another thread that is already inside `updateNode` takes
the `nodes_mutex` write lock next, expands its own node, walks every node in
`addEdges` and hits that connection:
Logical error: 'Processor ConvertingAggregatedToChunksWithMergingSource_64
was found as input for processor ConvertingAggregatedToChunksTransform_63,
but not found in list of processors'
which aborts the server in debug and sanitizer builds. Seen in the stress
test (arm_msan) with `memory_tracker_fault_probability` on a
`GROUP BY GROUPING SETS` query, where several `AggregatingTransform`s expand
the pipeline concurrently:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99495&sha=8e4aa21ffdd0b8611618c8e742e10b00af776955&name_0=PR&name_1=Stress%20test%20%28arm_msan%29
(PR ClickHouse#99495, which does not touch
the executor).
`updatePipeline` now marks the graph when it throws while recording an
expansion and keeps the new processors alive, since ports of live nodes point
at them; a later expansion sees the mark and returns `Cancelled` instead of
walking the inconsistent graph. The exception itself still propagates and
cancels the query as before.
The failure is injected through the new failpoint
`executing_graph_add_node_fail`, and the gtest drives `ExecutingGraph`
directly, because the window between the two expansions cannot be hit
reliably through the executor. Without the guard the test reproduces the
logical error above.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…n` rebases the cloned step `AggregationPushdown` clones the user's `AggregatingStep` and rebases the clone onto the join keys with `rebaseOntoInput`. `clone` carries `gradual_resize_enabled` over, so the pushed partial aggregation, an internal aggregation below the join, used the gradual pre-aggregation resize although the `*_for_gradual_resize` settings are documented to affect only the user's `GROUP BY` and the `AggregatingStep.h` comment lists Cascades pushdown among the internal aggregations that keep the strict resize. It was also observable: the original post-join step is planned with `storage_has_evenly_distributed_read = false`, so over a `Memory` / `numbers_mt` pushed side the copy reached the resize branch and built a `GradualResize` for an evenly distributed source. `rebaseOntoInput` now clears `gradual_resize_enabled` together with `group_by_keys_semantically_constant`. The gtest (renamed to `gtest_aggregating_step_rebase_clears_gradual_resize.cpp`) checks that the user's step builds `GradualResize` and that the clone-then-rebase copy, with or without the constant-keys mark, keeps the strict resize. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…k on the pushed clone `05243` runs a `GROUP BY` over a join that Cascades pushes below the join (the premise is checked with `EXPLAIN`), with `min_rows_per_stream_for_gradual_resize` set, and checks through `processors_profile_log` that the locally executed fragments build no `GradualResize`: the pushed partial aggregation is a rebased clone and the merge above the join is merge-only. The same query planned without the distributed planner is the positive control and does build one. Verified with a control binary without the `rebaseOntoInput` fix: the pushed query builds a `GradualResize` there (`05243_pushed 1`); with the fix the test passes 3/3. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Status after ee836c0 and b6b486c:
|
…essor # Conflicts: # src/Core/SettingsChangesHistory.cpp
The test sets `make_distributed_plan = 1` for the session, so the final query over `system.processors_profile_log` and `system.query_log` was also executed as a distributed plan. Those tables keep merging, and a part picked by the coordinator could be merged away before the worker read it, failing with `NO_SUCH_DATA_PART` in every flaky-check run. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99495&sha=b6b486ccb2545e6eef4b08b0f11e025848b1d8ab&name_0=PR #99495 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Status after 3904131 and 8e78d94:
|
After all outputs are activated, `routeDataStrict` paired input `i` with output `i` and only fell back to another output when the paired output had finished. When an input finished first, its output stayed idle for the rest of the query, so the pre-aggregation stage shrank to the number of still-running inputs (uneven parts, or an upstream filter that empties some streams). Now, when the paired output is busy, the chunk is handed to an output whose input has finished, like `StrictResizeProcessor` releases the output of a finished input. Outputs whose input is still running are left to that input. Addresses the AI review finding on `src/Processors/ResizeProcessor.cpp`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…y of gradual resize settings With `min_outstreams_per_resize_after_split` applied, the pre-aggregation stage starts with one active stream per split group, not a single stream. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…essor Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…essor # Conflicts: # src/Core/ProtocolDefines.h # src/Planner/Planner.cpp
…rging` step A step with `skip_merging` never takes the pre-aggregation resize, but neither `serialize` nor `clone` carries `skip_merging`, so a restored or cloned step merges and reaches the resize branch. Carrying the gradual bit there would build a `GradualResize` the original plan had ruled out, making the processor choice depend on the transport. Suppress the bit in both copies, like `serialize` already does for an evenly distributed read. `skip_merging` itself stays uncopied by `clone`: the clones made by `makeDistributed` and `applyParallelReplicas` become partial aggregations on another node, where the stream-disjointness it asserts is not known. New gtest `SkipMergingSuppressesGradualResizeInCopies`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Pushed 65b53a2. It merges master (conflicts in The previous head had two red @groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/36279360800/job/108551116630 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
The red is the performance dashboard's There is no fixing PR yet; this is the same gap as |
|
🕵 Thanks @groeneai. Agreed: |
|
missing c3 history should be now fixed |
|
🕵 Thanks @egor-click. On 65b53a2 every public CI check has now passed, including all |
|
🕵 |
|
Unconvincing. |
When ClickHouse processes GROUP BY, it often overestimates the number of threads needed. With
max_threads = 64but only a few thousand rows, all 64AggregatingTransforminstances get data, produce 64 partial hash tables, and the merge phase has to combine all of them — most nearly empty. This wastes time on merging overhead, which is especially noticeable for heavy aggregate states such asuniq,uniqExact,groupArray, etc.The new
GradualResizeProcessorstarts by pushing data to a single output port (or one port per split group whenmin_outstreams_per_resize_after_splitapplies), and activates all aggregation streams at once as soon as the configured row or byte threshold is crossed. For small datasets, only one aggregating thread receives data (or one per split group); for large datasets, all threads are used as before.New settings:
min_rows_per_stream_for_gradual_resize(default:0)min_bytes_per_stream_for_gradual_resize(default:0)Both settings default to
0, so the optimization is opt-in. Set either setting to a non-zero threshold to replace the pre-aggregationStrictResizewithGradualResizefor keyedGROUP BYqueries.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add opt-in settings
min_rows_per_stream_for_gradual_resizeandmin_bytes_per_stream_for_gradual_resizethat can improveGROUP BYperformance on small data volumes.Workflow [PR]
Sync PR [sync-upstream/pr/99495]