Skip to content

Parallelize merging of large uniqExact states in aggregation with keys - #117153

Merged
alexey-milovidov merged 46 commits into
masterfrom
parallel-keyed-uniq-exact-merge
Oct 23, 2026
Merged

alexey-milovidov merged 46 commits into
masterfrom
parallel-keyed-uniq-exact-merge

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Merging of large uniqExact states in GROUP BY queries (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:

  • mergeDataImpl merges each group's uniqExact set pairwise, source by source. The pool-taking UniqExactSet::merge bails 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.
  • The per-group merge work grows with the number of threads (every thread accumulates its own copy of the hot groups' values: 314 ms of merge CPU at 4 threads vs ~1.5 s at 96 threads for Q8), while the critical path — the largest group, here one dominant RegionID with 2.85M distinct users out of 18M pairs — stays on one thread inside its two-level bucket. Profiling showed one ConvertingAggregatedToChunksWithMergingSource busy 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-key COUNT(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:

  • mergeDataImpl gets a deferral mode (new IAggregateFunction::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.
  • After all sources of a single-level result / of a two-level bucket are processed, the deferred pairs are grouped by destination and each destination is merged with all of its sources in one parallelizeMergeMulti pass 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 to TwoLevelHashSet, 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.
  • This scattered merge runs only when the aggregator's pool has idle threads. When the pool is already busy, e.g. many groups of similar size are merged concurrently by the bucket workers, the sources are merged serially as before: the extra pass over the keys would not pay off.
  • parallelizeMergePrepare now uses ThreadPoolCallbackRunnerLocal and waits only for its own jobs. It can now be called by concurrently running two-level bucket mergers, where the previous bare ThreadPool::wait() would wait for unrelated jobs and could steal their exceptions.
  • AggregateFunctionUniqVariadic gets the same parallelizeMergePrepare/parallelizeMergeWithKey plumbing that the single-argument AggregateFunctionUniq already had.
  • The same deferral is applied on every keyed merge entrypoint: the two-level bucket merge (mergeBucketImpl), the serial single-level merge (mergeSingleLevelDataImpl), the default hash-partitioned single-level merge (mergeSingleLevelPartitionImpl), the parallel merge of single-level fixed hash maps for UInt8 / UInt16 keys (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 new IAggregateFunction::mergeBatchOrDefer that does not destroy the block-owned sources). In mergeBlocks the 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's thread_pool. The parallel merge of large states inside these jobs schedules nested jobs on thread_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 merged uniqExact states 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 hits table, 96-core aarch64, hot runs, interleaved A/B/A with the unpatched parent commit:

query master this PR speedup
Q8 (default threads) 0.20–0.25 s 0.068–0.075 s ~3x
Q9 0.21–0.25 s 0.078–0.10 s ~2.7x
Q8, max_threads=48 ~0.20 s 0.080 s 2.5x
Q8, max_threads=4 0.65–0.70 s 0.67–0.71 s unchanged
Q4 (without key, control) 0.044 s 0.044 s unchanged

The 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/uniqExactIf arguments, single-level and two-level result tables, external-aggregation spill, max_threads 2/16/96, group counts 3/100/20000) produced identical results; concurrent Q8/Q9 clients and max_execution_time cancellations 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

  • Merged into: 26.11.1.603-master (included in 26.11 and later)

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

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [89de047]

Summary: ✅


AI Review

Summary

The PR defers large keyed uniqExact merges and merges each destination with its sources in parallel, including several aggregate combinators and state-block merge paths. The earlier findings are addressed in the current code, but the supported Map combinator still bypasses the new merge contract. Request changes to implement that path or explicitly narrow the supported scope.

Findings

⚠️ Majors

  • src/Interpreters/Aggregator.cpp:4986: AggregateFunctionMap inherits the default false merge-capability and large-pair hooks. Its mergeImpl calls the serial nested merge at src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp:326. Thus grouped uniqExactMap(map('x', n)) retains the serial per-group merge bottleneck even with a single map key and large partial states. Forward the hooks and merge nested states by map key, or explicitly exclude Map from the advertised combinator support.
Tests
  • ⚠️ 05059_group_by_uniq_exact_parallel_merge has no Map coverage. Add one hot-key uniqExactMap case and verify through profiling or a breakpoint that its large states reach the deferred multi-way merge if this path is included in scope. This review used source tracing and existing CI/discussion evidence; no local server build was available for a new runtime reproduction.
Final Verdict

⚠️ Request changes — implement deferred merging for Map with focused coverage, or explicitly document that it remains outside the supported combinator scope.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 30, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 89de0473a with master e031bc0b0 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

163 object files changed (+2.06 MiB total), 0 added.

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.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 4 query(s) improved out of 31 analysed

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 · ⚠️ 1 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 8 improvement 333 279 -16.2% <0.0001 aggregation: COUNT(DISTINCT UserID) GROUP BY RegionID merges per-group uniqExact states, which this PR now defers and merges in parallel. Wall time is -16.2% while CPU is about flat, which fits better parallelism.
🟢 9 improvement 380 333 -12.3% <0.0001 aggregation: Same RegionID grouping with a COUNT(DISTINCT UserID) state, so it goes through the new deferred parallel uniqExact merge. Wall time is -12.3% with CPU nearly unchanged.
🟢 10 improvement 162 106 -34.6% <0.0001 aggregation: COUNT(DISTINCT UserID) grouped by MobilePhoneModel runs the large-state uniqExact merge this PR parallelizes. The -34.6% wall-time drop with flat CPU points to less serial merge time.
🟢 11 improvement 188 146 -22.3% <0.0001 aggregation: Grouped COUNT(DISTINCT UserID) over MobilePhone and MobilePhoneModel goes through the new deferred uniqExact merge path. The -22.3% gain with steady CPU fits the intended effect.
⚠️ 32 not_sure 716 792 +10.5% 0.0001 aggregation: A high-cardinality GROUP BY with only count/sum/avg, so there is no uniqExact state to defer. The two tests disagree and the measurements are very noisy, so +10.5% stays inconclusive.

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
  • StressHouse run: ae62c5a0-dc60-4da5-8afe-b7a27a11646d
  • MIRAI run: 3eaaba8f-baf0-4f82-b17f-af394642e0ea
  • PR check IDs:
    • clickbench_1032315_1791802584
    • clickbench_1032321_1791802584
    • clickbench_1032343_1791802584
    • tpch_adapted_1_official_1032357_1791802584
    • tpch_adapted_1_official_1032371_1791802585
    • tpch_adapted_1_official_1032385_1791802585

Comment thread src/Interpreters/Aggregator.cpp Resolved
… 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]>
alexey-milovidov and others added 2 commits September 16, 2026 08:06
…-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]>
Comment thread src/AggregateFunctions/UniqExactSet.h Resolved
@Algunenano
Algunenano removed their request for review September 24, 2026 09:58
alexey-milovidov and others added 3 commits September 26, 2026 19:40
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 80ee555 (merge of master plus both AI-review Majors: empty sources are no longer deferred, and -OrNull/-OrDefault now join the deferred merge; 05059 extended).

Previous reds on 91c91fe: the Stress test (arm_asan_ubsan, s3) UBSan at StorageDistributed.cpp:773 is #121464, fixed by #121418, which the master merge pulls in. The Performance Comparison (arm_release, 1/6) regression is array_first_last #9, which does not aggregate at all.

@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 (array_first_last #9 +19%) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Interpreters/Aggregator.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. It is not caused by this PR: array_first_last #9 is SELECT arrayLast(x -> x > 3, x) FROM array_first_last_32 over a Memory table with max_threads = 1, so nothing in it aggregates.

The shard's own report did not flag it: +19.2% is under the query's learned threshold of 27% (changed_threshold in all-query-metrics.tsv). The check failed on the dashboard tier alone. The dashboard reports no recent master history for this query (it has history for the other rows of that run, e.g. rand), so it compared the change with its 2.0% default floor.

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 #11 (the same arrayLast code on the 128-element table) took 54-55 ms on both. Over the last 13 days, 291 of 3879 ARM runs showed #9 more than 15% slower and 285 more than 15% faster, including 30 and 39 of the 413 master runs. Its arrayFirst twin on the same table (#8) moved that much in 4 of 3874 runs, and #11 has the same two-mode shape (352 of 3883).

No open PR covers these queries (#122458 stabilizes four others). I will send a PR for the two arrayLast filter queries of this test and link it here.

alexey-milovidov and others added 5 commits October 14, 2026 09:52
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check at 8f1fc677 was 05345_text_index_prewhere_read_step_order in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117153&sha=8f1fc677c0fbbbcf5804b4ea4bcc0183b592bd1f&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29). It is unrelated: it fails the same way on master and on dozens of other PRs. Its fix, #125892, has landed on master, so I merged master (0b94501). The merged tree builds, and 05059_group_by_uniq_exact_parallel_merge passes locally three times out of three.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Update: I merged master (01f861c). The CI failures at 0b94501d are unrelated to this PR:

  • 05339_string_filters_during_scan_parquet_short_dictionary_values failed in every stateless job. It was broken on master as well, and master fixed it in 12fd7bc (it pins use_columns_cache = 0), which this merge brings in.
  • 04034_autopr_min_rows_per_replica_reuses_index_analysis (ParallelReplicas) is flaky across many PRs. Fix flaky automatic parallel replicas tests that read a compressible table #125544 fixes it.
  • Performance Comparison: join_planning_pruned_statistics #0 is an EXPLAIN query (join planning only, no aggregation), and its +19.3% is exactly at the noise threshold. The uniqExact queries got faster: uniqExactIf #4 is about 4x faster, and clickbench #10 / #11 are 15-40% faster.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 (05024_autopr_plan_based_parallel_replicas: pr_used is 0 instead of 1 for the second query) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR: since 2026-10-10 it has failed on about 18 PRs and on master, after #125544 was merged.

I merged master again (536cf3f). It merged cleanly, clickhouse builds, and 05059_group_by_uniq_exact_parallel_merge passes locally.

@groeneai

Copy link
Copy Markdown
Collaborator

This is fixed by #125544, merged 2026-10-19 21:46Z. query_1 with pr_used 1 -> 0 is the signature it targets: the shared table's 7 MB read compressed to ~131 KB, so the input_bytes > 2 * output_bytes gate depended on a noisy output estimate. The PR stores WatchID with CODEC(NONE) so the read stays large.

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 arm_binary jobs). No new PR is needed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Update: I merged master (89de047).

if (is_skipped(i))
continue;

if (deferred && aggregate_functions[i]->isAbleToParallelizeMerge())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Forward the deferred merge through 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is okay.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 23, 2026
Merged via the queue into master with commit 6f56968 Oct 23, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the parallel-keyed-uniq-exact-merge branch October 23, 2026 02:09
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 23, 2026
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
… 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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
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]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
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]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
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]>
arthurpassos added a commit to Altinity/ClickHouse that referenced this pull request Nov 18, 2026
…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]>
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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants