Repository navigation
Parallelize merging of large uniqExact states in aggregation with keys - #117153
Conversation
Merging partial aggregation states for GROUP BY x, uniqExact(y) (also spelled COUNT(DISTINCT y)) was single-threaded per group: mergeDataImpl merged each group's set serially, and UniqExactSet::merge bails out to a serial merge whenever the source set is single-level, which is exactly what the per-thread partial sets are on machines with many cores (each thread sees < 100k distinct values per group). The more cores, the more partial copies of the hot groups' sets have to be merged, so the total merge work grows with the thread count while its critical path (the biggest group, e.g. one dominant RegionID in ClickBench Q8) stays on one thread. Q8 hot runs have been flat at ~0.25s on c6a.metal since 2022 while the without-key COUNT(DISTINCT) (Q4) got 20x faster from parallel merging. Now mergeDataImpl defers pairs of states that are past the two-level threshold (via the new IAggregateFunction::mergeAndDestroyBatchOrDefer), and after all sources are collected, each destination is merged with all its sources in one parallelizeMergePrepare + parallelizeMergeMulti pass on the shared thread pool: single-level partials are converted to two-level in parallel and then all 256 sub-buckets are merged across all sources in parallel. parallelizeMergePrepare now waits only for its own jobs (it can be called by concurrent two-level bucket mergers, where a bare ThreadPool::wait() would wait for unrelated jobs and steal their exceptions). AggregateFunctionUniqVariadic gets the same parallelizeMergePrepare/parallelizeMergeWithKey plumbing as the single-argument function. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [89de047] Summary: ✅
AI ReviewSummaryThe PR defers large keyed Findings
Tests
Final Verdict
|
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o |
12.23 MiB | 13.19 MiB | +978.44 KiB (+7.81%) |
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o |
26.44 MiB | 26.63 MiB | +197.94 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o |
6.79 MiB | 6.83 MiB | +45.43 KiB (+0.65%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o |
6.97 MiB | 7.02 MiB | +45.12 KiB (+0.63%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… |
5.81 MiB | 5.85 MiB | +40.03 KiB (+0.67%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… |
5.73 MiB | 5.76 MiB | +30.15 KiB (+0.51%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/SingleValueData.cpp.o |
899.70 KiB | 929.30 KiB | +29.60 KiB (+3.29%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o |
3.76 MiB | 3.78 MiB | +28.00 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined2… |
3.07 MiB | 3.09 MiB | +22.98 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.98 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.98 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.97 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.97 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.97 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.97 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.97 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
3.07 MiB | 3.09 MiB | +22.97 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… |
13.58 MiB | 13.60 MiB | +21.68 KiB (+0.16%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… |
2.94 MiB | 2.96 MiB | +19.30 KiB (+0.64%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… |
16.00 MiB | 16.02 MiB | +18.04 KiB (+0.11%) |
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Compile time of recompiled translation units
573 translation units recompiled, 4939 s compile time in total, 573 of them have a recent master baseline.
|
📊 Cloud Performance Report 🟢 AI verdict: This PR makes four ClickBench queries faster: Q8 (-16.2%), Q9 (-12.3%), Q10 (-34.6%) and Q11 (-22.3%). All four are GROUP BY queries with COUNT(DISTINCT UserID), which is exactly the large uniqExact merge path the PR now defers and runs in parallel. CPU time is nearly unchanged on all four while wall time drops, so the merge work is spread across more threads rather than reduced, which matches the PR's design. Q32 (+10.5%) is inconclusive: it uses no uniqExact state, the two tests disagree and its measurements are very noisy, so it does not point to a regression. clickbench🟢 4 improved · Flagged queries (5 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
… paths too The deferred multi-way parallel merge of large `uniqExact` states was only wired into `mergeDataImpl`, which is reached from `mergeSingleLevelDataImpl` and `mergeBucketImpl`. Two keyed merge entrypoints still merged every pair of large states serially: - `mergeSingleLevelPartitionImpl`, the default single-level merge with `enable_parallel_single_level_merge = 1`, flushed duplicates through the old pairwise `mergeAndDestroyBatch` loop. It now collects the large pairs with `mergeAndDestroyBatchOrDefer` and merges each destination with all of its sources in one `parallelizeMergePrepare` + `parallelizeMergeMulti` pass after the last source, like the other two paths. - `mergeStreamsImplCase`, which merges blocks of partial states (`mergeOnBlock`, `mergeBlocks`: distributed, memory-efficient and external aggregation), called `mergeBatch`, so two single-level partial states were merged serially. The new `IAggregateFunction::mergeBatchOrDefer` collects the large pairs and `mergeDeferredLargeStates` merges them in parallel without destroying the sources, which stay owned by the aggregate columns of the block (the same way the without-key stream merge already converts block-owned states in place). `UniqExactSet::worthMergingInParallel` no longer defers a merge into an empty destination, which `merge` handles by adopting the source's two-level set. The test is renumbered to `05059` (the `05054` prefix is already taken on master) and gets cases for the partitioned and the serial single-level merge, for `remote()` with and without memory-efficient merging (two-level and single-level partial states), and for the spill-to-disk read-back merge. Verified locally against a private server: the single-level `remote()` case now records `UniqExaConvert` and `UniqExactMerger` threads, which only the deferred path produces. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…-exact-merge # Conflicts: # src/Interpreters/Aggregator.cpp
…ators `isLargeMergePair` is now a virtual hook of `IAggregateFunction` (the batch helpers still call it devirtualized), and the `-If`, `-Array`, `-State`, `-Merge`, `-Tuple` combinators and the `Nullable` adapter forward it to the nested function, so wrapped `uniqExact` states are deferred by `mergeBatchOrDefer` / `mergeAndDestroyBatchOrDefer` like the plain ones. The `-Tuple` combinator defers the whole tuple state as soon as one nested pair is large. The wrappers also forward `isParallelizeMergePrepareNeeded`, which they never did: without it the deferred single-level sets skipped the parallel two-level conversion and were merged serially. The test also gets cases for `uniqExactIf`, `uniqExactTuple` and a `Nullable` argument on the keyed, remote state-block and spilled-state merge paths, and its data sizes are cut by about 4x: the flaky check runs it repeatedly and hit the 180 s budget. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117153&sha=0cacc777295a13bb86f2c43a28a9cb196eee0b08&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29 PR: #117153 Co-Authored-By: Claude Fable 5.1 <[email protected]>
An empty source (`uniqExactIf` where the predicate never matched, all-`NULL` input under the `Nullable` adapter) makes `merge` a no-op, but `worthMergingInParallel` returned `true` for it once the destination was two-level, so it was deferred, converted to two-level and merged through `parallelizeMergeMulti` for nothing. Add a selective case to `05059`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ll`/`-OrDefault` `AggregateFunctionOrFill` did not forward `isAbleToParallelizeMerge`, `isParallelizeMergePrepareNeeded` and `isLargeMergePair`, so `uniqExactOrNull`/`uniqExactOrDefault` stayed on the serial keyed merge. Forward them (and `parallelizeMergePrepare`, the thread-pool `merge` and `parallelizeMergeMulti`) to the nested function, folding the trailing presence byte separately. Cases added to `05059` in the previous commit. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Pushed 80ee555 (merge of master plus both AI-review Majors: empty sources are no longer deferred, and Previous reds on 91c91fe: the @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117153&sha=91c91fec7f68ef07d99fba70b392819adf6a7256&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 ( |
|
Investigated. It is not caused by this PR: The shard's own report did not flag it: +19.2% is under the query's learned threshold of 27% ( The query is bimodal on the ARM runners, independently of the code. In that job all 7 runs took 53.1-53.6 ms on the old server and 63.1-64.4 ms on the new one, while No open PR covers these queries (#122458 stabilizes four others). I will send a PR for the two |
…lti-way merge `parallelizeMergeMulti` of the `ArgMin` / `ArgMax` combinators selected the sources by `isEqualTo` with the final key, which excluded the source that had installed a `NaN` key, so e.g. `uniqExactArgMinIf(n, nan, n = 777777)` returned 0 instead of 1 in the merge without keys. Select the same sources as the serial merge: the one that installed the final key and the later ones having an equal key. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rameter` in `Aggregator` The `is_skipped` lambda in `mergeAndDestroyDetachedBatch` does not use its parameter when `USE_EMBEDDED_COMPILER` is off (Fast test), and clang-tidy wants `isRecordedDeferredPair` to take `ConstAggregateDataPtr`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117153&sha=latest&name_0=PR&name_1=Build%20(arm_tidy%2C%203%2F4) #117153 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ggregateFunctionHelper` They were instantiated for every aggregate function and combinator type (about 6200 instantiations, 1.8 MB of code in `src/AggregateFunctions` alone without sanitizers). Under MSan, this pushed `unit_tests_dbms` in the private build over the 2 GiB reach of `R_X86_64_PC32` relocations, failing the link and the "CH Inc sync" check. They are only called when `isAbleToParallelizeMerge` is true, i.e. for `uniqExact` and combinators wrapping it, whose merges are expensive, so a single implementation in `IAggregateFunction` with virtual calls is enough. Related: ClickHouse/clickhouse-private#71635 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The only red check at |
|
🕵 Update: I merged master (01f861c). The CI failures at
|
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117153&sha=01f861c42861796612c4b2f6684e8ce6657f3d05&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel%29 ( I merged master again (536cf3f). It merged cleanly, |
|
This is fixed by #125544, merged 2026-10-19 21:46Z. The failing run here (01f861c, 2026-10-18 16:24Z) predates that merge, and your master merge 536cf3f contains it. In CIDB all 18 failures since 2026-10-10 (16 PRs, 2 on master) are before the merge; since then there are 0 failures in 3690 runs (479 on master, 1747 in the four |
|
🕵 Update: I merged master (89de047).
|
| if (is_skipped(i)) | ||
| continue; | ||
|
|
||
| if (deferred && aggregate_functions[i]->isAbleToParallelizeMerge()) |
There was a problem hiding this comment.
Map too.
This gate still excludes AggregateFunctionMap: it inherits isAbleToParallelizeMerge = false and isLargeMergePair = false, and its only mergeImpl calls the serial nested merge for each map key (src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp:290–326). Consequently, a grouped uniqExactMap(map('x', n)) with one hot group and large partial sets never reaches either deferred batch helper or the multi-way parallel merge. A one-entry map carries the same large uniqExact state as the one-element ForEach / one-bucket Resample cases added here, but still retains the serial merge bottleneck.
Please forward the merge capability, large-pair detection, and parallel merge hooks through Map, grouping nested states by map key, and add one focused hot-key case. Alternatively, explicitly document Map as excluded from the combinator support claimed for this change.
… throws The map `mergeDataImpl` (serial single-level merge, two-level bucket merge, parallel fixed hash map merge) and the non-indexed loop of `mergeSingleLevelPartitionsImpl` take the state of a key found in both tables out of the source table (`src = nullptr`) and queue it in a local `PaddedPODArray` for `mergeAndDestroyDetachedBatch`. Until that call nothing owns the queued states: a throw in between, e.g. `MEMORY_LIMIT_EXCEEDED` from the destination `HashTable::resize`, leaked their heap buffers, since the catches destroyed only the deferred pairs. ClickHouse#117153 made the window after the batch starts exception-safe; this closes the collection window before it. Extract the cleanup loop of `mergeAndDestroyDetachedBatch` into `destroyDetachedSources` and call it from a catch around the collection of `mergeDataImpl` (the JIT merge and the batch call stay outside the try, the batch owns the states from there) and from the existing catch of the partition merge. `flush_merges` clears its arrays in a `SCOPE_EXIT`, because the batch takes the states also when it throws, so a state is never destroyed twice. Deferred pairs come only from batches that started and the queued states only from batches that did not, so the two cleanups are disjoint. The new ONCE failpoint `aggregator_merge_collect_states_throw` throws at the end of a collection while states are queued. The test runs it on six paths in `clickhouse local`, whose LeakSanitizer check at exit aborts on a leak. `IAggregateFunctionHelper::mergeAndDestroyBatch` and the `-Tuple` combinator also destroy the rest of their batch when a merge throws, as `mergeAndDestroyBatchOrDefer` does; the second ONCE failpoint `aggregator_merge_batch_throw` tests a throw inside the batch in both merges. Related: ClickHouse#131315 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the five conflicts of the 26.8 cherry-pick of ClickHouse#131595. They are all regions where master has code that 26.8 does not have: the deferral of large merges (ClickHouse#117153: mergeAndDestroyBatchOrDefer, DeferredMerges, mergeAndDestroyDetachedBatch and its catch), isSelfMerge (ClickHouse#130678), the bound of zero-sized nested states (ClickHouse#130120), and the partition-by-partition merge of the adaptive aggregator (ClickHouse#129565). None of them is labelled for 26.8, and the resolution takes none of them. 26.8 has no catch around the per-function loop of the batch merge (master got it in ClickHouse#117153), so a throw in the merge of one function would still leak the queued states of every function after it. The resolution adds a 26.8 mergeAndDestroyDetachedBatch, the master function without the deferral: the per-function loop, and a catch that destroys the states of the following functions. The map mergeDataImpl (also the JIT path) and the flush of mergeSingleLevelPartitionImpl call it. The collection loop of mergeSingleLevelPartitionImpl is wrapped in the try of ClickHouse#131595, so it is re-indented. In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.8 assertion is kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the five conflicts of the 26.9 cherry-pick of #131595. They are all regions where master has code that 26.9 does not have: the deferral of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges, mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the bound of zero-sized nested states (#130120), and the partition-by-partition merge of the adaptive aggregator (#129565). None of them is labelled for 26.9, and the resolution takes none of them. 26.9 has no catch around the per-function loop of the batch merge (master got it in #117153), so a throw in the merge of one function would still leak the queued states of every function after it. The resolution adds a 26.9 mergeAndDestroyDetachedBatch, the master function without the deferral: the per-function loop, and a catch that destroys the states of the following functions. The map mergeDataImpl (also the JIT path) and the flush of mergeSingleLevelPartitionImpl call it. The collection loop of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it is re-indented. In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.9 assertion is kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the five conflicts of the 26.10 cherry-pick of #131595. They are all regions where master has code that 26.10 does not have: the deferral of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges, mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the bound of zero-sized nested states (#130120), and the partition-by-partition merge of the adaptive aggregator (#129565). None of them is labelled for 26.10, and the resolution takes none of them. 26.10 has no catch around the per-function loop of the batch merge (master got it in #117153), so a throw in the merge of one function would still leak the queued states of every function after it. The resolution adds a 26.10 mergeAndDestroyDetachedBatch, the master function without the deferral: the per-function loop, and a catch that destroys the states of the following functions. The map mergeDataImpl (also the JIT path) and the flush of mergeSingleLevelPartitionImpl call it. The collection loop of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it is re-indented. In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.10 assertion is kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ggregate_merge_work` The variadic `uniqExact` of this build has no preparation step of the parallel merge: it came with ClickHouse#117153, which was not backported. CI: `AggregateMergeWork.VariadicAndTupleArguments` of `Unit tests (asan_ubsan)`, pull request 2889. Signed-off-by: Arthur Passos <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Merging of large
uniqExactstates inGROUP BYqueries (e.g.SELECT k, COUNT(DISTINCT x) ... GROUP BY k) is now parallelized, the same way it has long been for the without-key case. ClickBench Q8/Q9 hot runs get ~3x faster on many-core machines.Documentation entry for user-facing changes
Investigating why ClickHouse is ~3x slower than the fastest entries on ClickBench Q8 (
SELECT RegionID, COUNT(DISTINCT UserID) ... GROUP BY RegionID) on c6a.metal showed the merge of partial aggregation states is the bottleneck, and it is single-threaded per group:mergeDataImplmerges each group'suniqExactset pairwise, source by source. The pool-takingUniqExactSet::mergebails out to a fully serial merge whenever the source set is single-level — which is exactly what the per-thread partial sets are on machines with many cores (each thread sees fewer than 100k distinct values per group, below the two-level threshold). A single-level destination also never converts to two-level during merging.RegionIDwith 2.85M distinct users out of 18M pairs — stays on one thread inside its two-level bucket. Profiling showed oneConvertingAggregatedToChunksWithMergingSourcebusy 170 ms of a 232 ms query. This is also why Q8 hot time on c6a.metal has been flat (~0.25–0.30 s) since 2022 while Q4 (without-keyCOUNT(DISTINCT)) got 20x faster from the parallel merge of PR Optimize merge of uniqExact without_key #43072 / Convert hashSets in parallel before merge #50748.What this PR does:
mergeDataImplgets a deferral mode (newIAggregateFunction::mergeAndDestroyBatchOrDefer): for functions that can parallelize their merge, pairs of states past the two-level threshold (UniqExactSet::worthMergingInParallel) are collected instead of merged in place. Small states merge exactly as before.parallelizeMergeMultipass on the aggregator's thread pool: the keys of single-level partial states are grouped by sub-bucket into flat arrays in parallel (they are not converted toTwoLevelHashSet, which costs at least 256 hash tables of the initial size per state, far more than a small per-thread state itself), then all 256 sub-buckets of the destination absorb their share of all sources in parallel.parallelizeMergePreparenow usesThreadPoolCallbackRunnerLocaland waits only for its own jobs. It can now be called by concurrently running two-level bucket mergers, where the previous bareThreadPool::wait()would wait for unrelated jobs and could steal their exceptions.AggregateFunctionUniqVariadicgets the sameparallelizeMergePrepare/parallelizeMergeWithKeyplumbing that the single-argumentAggregateFunctionUniqalready had.mergeBucketImpl), the serial single-level merge (mergeSingleLevelDataImpl), the default hash-partitioned single-level merge (mergeSingleLevelPartitionImpl), the parallel merge of single-level fixed hash maps forUInt8/UInt16keys (mergeSingleLevelDataImplFixedMap, each worker merges the deferred pairs of the keys it owns), and the merge of blocks of partial states (mergeStreamsImplCase, used by distributed, memory-efficient, in-order and external aggregation via a newIAggregateFunction::mergeBatchOrDeferthat does not destroy the block-owned sources). InmergeBlocksthe deferred pairs are collected across all blocks, so that a destination with one source per block (e.g. one per stream in aggregation in order) is merged once with all of them.mergeBlocks(non-memory-efficient distributed merge) runs its per-bucket merges on a separate pool instead of the aggregator'sthread_pool. The parallel merge of large states inside these jobs schedules nested jobs onthread_pool; when the outer jobs occupied all its threads and queue slots, the nested jobs could never be scheduled and the query hung (not cancellable). This was already possible on master when both mergeduniqExactstates were two-level; the deferral made it much more likely. The same fix has since been merged separately in Fix deadlock in non-memory-efficient merge of two-level aggregation blocks #123352, so it now comes from master.Results on the 100M-row ClickBench
hitstable, 96-core aarch64, hot runs, interleaved A/B/A with the unpatched parent commit:max_threads=48max_threads=4The busiest merger's own busy time drops from ~170 ms to ~22 ms, and Q8 now scales with cores again instead of flattening at 16 threads. This puts ClickHouse at parity with the fastest ClickBench entry on this query (measured side by side on the same machine, where Firebolt — which plans grouped
COUNT(DISTINCT)as dedup-then-count — runs Q8 in 0.074–0.093 s).Verification besides the new functional test: a 108-case differential fuzz against the unpatched binary (UInt64/String/Nullable/variadic/
uniqExactIfarguments, single-level and two-level result tables, external-aggregation spill,max_threads2/16/96, group counts 3/100/20000) produced identical results; concurrent Q8/Q9 clients andmax_execution_timecancellations at 10–120 ms cut points ran clean with no server errors.Follow-ups not covered here: the key8/key16 fixed-map merge path (
ParallelMergeWorker) is unchanged.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117153]
Version info
26.11.1.603-master(included in26.11and later)