Skip to content

Add GradualResizeProcessor to limit effective parallelism for GROUP BY on small data volumes - #99495

Closed
alexey-milovidov wants to merge 211 commits into
masterfrom
gradual-resize-processor
Closed

alexey-milovidov wants to merge 211 commits into
masterfrom
gradual-resize-processor

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 14, 2026 •

Copy link
Copy Markdown
Member

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, which is especially noticeable for heavy aggregate states such as uniq, uniqExact, groupArray, etc.

The new GradualResizeProcessor starts by pushing data to a single output port (or one port per split group when min_outstreams_per_resize_after_split applies), 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-aggregation StrictResize with GradualResize for keyed GROUP BY queries.

Changelog category (leave one):

  • Performance Improvement

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_resize and min_bytes_per_stream_for_gradual_resize that can improve GROUP BY performance on small data volumes.


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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [65b53a2]

Summary: ✅


AI Review

Summary

This PR adds the opt-in GradualResize path for ordinary hash-based GROUP BY pre-aggregation, carries that decision through planner/serialization carriers, and adds focused coverage for split resize, shipped plans, correlated subqueries, and aggregation pushdown. I reviewed the current head against the full PR diff and prior discussion, and I did not find a remaining actionable correctness, compatibility, or coverage issue in the current code.

Final Verdict

✅ Approve.

LLVM Coverage Report

Measured on commit 65b53a2.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.50% -0.10%

Changed lines: Changed C/C++ lines covered: 372/383 (97.13%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 14, 2026
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]>
Comment thread src/Processors/ResizeProcessor.cpp Resolved
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]>
@nihalzp nihalzp self-assigned this Mar 14, 2026
alexey-milovidov and others added 2 commits March 15, 2026 02:31
- 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]>
alexey-milovidov and others added 2 commits March 16, 2026 21:50
…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]>
Comment thread src/Processors/ResizeProcessor.cpp Resolved
Comment thread .claude/learnings.md Resolved
@nihalzp

nihalzp commented Mar 17, 2026

Copy link
Copy Markdown
Member

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 setNeeded, the upstream transform sees that it cannot push which then propagates and linearize the pipeline till we have reached enough rows to unlock more ports. This can be bad if the previous transform is a FilterTransform which filters out all of the rows, and our entire pipeline stays linear forever (to be more precision, parallelism collapses to the current number of active outputs.)

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.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

One idea could be that we keep all the input ports and gradually allow output ports.

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]>
alexey-milovidov added a commit that referenced this pull request Mar 18, 2026
…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]>
Comment thread src/Processors/ResizeProcessor.cpp Resolved
alexey-milovidov and others added 3 commits March 19, 2026 07:25
…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]>
alexey-milovidov and others added 2 commits September 22, 2026 11:51
…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]>
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 22, 2026
…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]>
alexey-milovidov and others added 2 commits September 22, 2026 23:26
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status after ee836c0 and b6b486c:

  • AI Review Major (clone rebased by AggregationPushdown kept gradual_resize_enabled): fixed. rebaseOntoInput now clears the mark. The gtest gtest_aggregating_step_rebase_clears_gradual_resize.cpp covers it, and the new stateless test 05243_gradual_resize_cascades_aggregation_pushdown covers it end to end. A control binary without the fix fails 05243, and the fixed binary passes it 3/3. The thread is answered and resolved.
  • The CI reds on cab12b2 are unrelated to this PR:

alexey-milovidov and others added 2 commits September 23, 2026 03:59
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status after 3904131 and 8e78d94:

  • Conflict resolved: merged master (741 commits behind). The only conflict was SettingsChangesHistory.cpp in the 26.10 block; kept both sides. Plan serialization versions don't collide (master is on 20, this PR uses 21).
  • CI red fixed, caused by this PR: all 7 failing jobs failed on the new test 05243_gradual_resize_cascades_aggregation_pushdown, including the five flaky checks. The session-level make_distributed_plan = 1 also covered the final query over system.processors_profile_log / system.query_log. Those tables keep merging, so a part the coordinator picked could be merged away before the worker read it, and the query failed with NO_SUCH_DATA_PART. That query now runs with the distributed planner and Cascades turned off.
  • Checked locally on the merged build: 05243 passed 10 of 10 repeated runs, and all 8 *_gradual_resize_* stateless tests pass (05056 / 05182 need the shipped-plan config and were left to CI).
  • 0 unresolved review threads. On the previous head the AI Review verdict was Approve.

Comment thread src/Processors/ResizeProcessor.cpp Resolved
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]>
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
…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]>
alexey-milovidov and others added 2 commits September 28, 2026 09:06
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 65b53a2. It merges master (conflicts in ProtocolDefines.h and Planner.cpp resolved: master added QUERY_CONDITION_CACHE_FLAG = 19 alongside our 21, and addAggregationStep now takes both settings/trivial_group_by_limit and group_by_keys_semantically_constant) and addresses both open skip_merging review threads. ninja clickhouse unit_tests_dbms builds cleanly and 19/19 AggregatingStep*/GradualResize* gtests pass.

The previous head had two red Performance Comparison (amd_release) shards, and both are unrelated to this PR. On 3/6 the only change was enum #4 at +25.0%, exactly the threshold. That query is an Enum8 cast with no GROUP BY, and the gradual-resize settings default to 0. Shard 5/6 reported no query changes at all.

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

@groeneai

Copy link
Copy Markdown
Collaborator

The red is the performance dashboard's confirmed_regression on to_valid_utf8 #1 (0.0081 -> 0.0096 s, +18.3%), and it is not a regression. The dashboard scored it without master history (C3: "No recent master history is available", so a 2% floor), although it serves 353 amd master points for this query. The outlier is the reference side: the same reference build (010807a3) ran this query at a median 0.0100 s over 40 amd runs and 0.0081 s is its second-fastest, while the PR side's 0.0096 s is ordinary. The dashboard's own C6 module also rates the baseline side as the more anomalous one (4.83 vs 1.41). The query is otherwise stable (3 of 1154 amd runs above +15% in 30 days), so a test change would not help.

There is no fixing PR yet; this is the same gap as group_uniq_array #7 on #100330. @egor-click, @ fm4v pointed me to you for the dashboard: should this be fixed in the dashboard, by using that history for C3, or should I send the in-tree fallback from #100330 (comment) (a confirmed_regression scored without master history fails the shard only if the shard's own report also calls the query slower)? The fallback would have kept this shard green.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. Agreed: to_valid_utf8 #1 has no GROUP BY, and both gradual-resize settings default to 0, so this PR does not touch that shard. Nothing changes here. Whether the dashboard or the in-tree fallback should fix the missing master history in C3 is for @egor-click to decide, separately from this PR. The CI run on 65b53a2 is still in progress and has no failures so far, and there are 0 unresolved review threads.

@egor-click

Copy link
Copy Markdown
Contributor

missing c3 history should be now fixed

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @egor-click. On 65b53a2 every public CI check has now passed, including all Performance Comparison shards. The only check still pending is CH Inc sync. There are 0 unresolved review threads, so nothing more needs to change on this branch.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync had been stuck at pending since 2026-09-28. The cause was the private sync PR: it was frozen at its 2026-09-14 tip and CONFLICTING, so new public heads were never merged into it. I merged private master and then 65b53a2 into it by hand. Private master already uses plan serialization versions 20 and 21, so on the private side the Aggregating step-version gate (DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_SEMANTICALLY_CONSTANT_GROUP_BY_KEYS) and the global version are 22. The public branch keeps 21. The sync PR is now MERGEABLE, and private CI is running. The public branch is unchanged: all public checks are green, the AI review approves, and there are 0 unresolved threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Unconvincing.

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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants