Skip to content

Parallelize the final merge of single-level aggregation hash tables - #110395

Merged
nihalzp merged 26 commits into
ClickHouse:masterfrom
nihalzp:parallel-single-level-merge
Jul 28, 2026
Merged

nihalzp merged 26 commits into
ClickHouse:masterfrom
nihalzp:parallel-single-level-merge

Conversation

@nihalzp

@nihalzp nihalzp commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

In a parallel GROUP BY, every thread aggregates into its own hash table. When those tables stay below the two-level threshold, the final merge combined them serially on one thread.

This PR merges them in parallel: the key space is split into disjoint partitions by key hash, and each partition is merged independently by one of the threads — a merging thread reads all hash tables tables (this is okay because the hash tables are already small) and combines the keys that belong to its partition, so no two threads ever touch the same key. Controlled by the new setting enable_parallel_single_level_merge (enabled by default).

ClickBench:

image

TPCDS

image

Others

image image image

There are some slowdowns in the performance tests but none of them are related and they are already flaky in master (verified with Claude).

Changelog category (leave one):

  • Performance Improvement

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

Parallelize the final merge of single-level aggregation hash tables: the key space is split into disjoint hash partitions that the threads merge independently (setting enable_parallel_single_level_merge, enabled by default). Speeds up GROUP BY queries whose per-thread hash tables stay below the two-level threshold but whose merge dominated the runtime.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [da301c9]

Summary: ✅


AI Review

Summary

This PR adds a new enable_parallel_single_level_merge path that hash-partitions the final merge of per-thread single-level aggregation hash tables and wires the setting through the main aggregation entrypoints. The core implementation looks solid, but one reachable family of single-level methods still falls outside both parallel merge paths while the new setting text now suggests that only plain key8 / key16 are special-cased.

Findings

⚠️ Majors

  • [src/Processors/Transforms/AggregatingTransform.cpp:648] enable_parallel_single_level_merge still falls back to the serial merge for several normal single-level methods: keys16, nullable_key8 / nullable_key16, and low_cardinality_key8 / low_cardinality_key16. AggregatedDataVariants::chooseAggregationMethod selects those for ordinary GROUP BY shapes, but worthParallelMergeSingleLevel only recognizes plain key8 / key16 and this gate rejects the rest because they have no two-level counterpart. That means the setting and its updated description still over-promise coverage, and users get no speedup on those queries despite enabling it.
    Suggested fix: either extend a parallel merge path to those variants, or narrow the setting text and coverage so they explicitly say these small-key methods also remain serial.
Final Verdict

Changes requested until the setting contract matches the actual set of single-level methods that can use the new parallel merge.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 14, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
@yariks5s yariks5s self-assigned this Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 regressed, 6 improved out of 37 analysed

Release-transition baseline: compared against the last 26.7 master because no 26.8 master baseline exists at or before the trusted base-commit anchor.

This PR parallelizes the final merge of per-thread single-level aggregation hash tables (new setting enable_parallel_single_level_merge, defaulted on), splitting the key space into disjoint hash partitions merged independently. The ClickBench improvements line up cleanly with that: the wins are all GROUP BY queries (Q12, Q13, Q18, Q32-Q34, ×2 faster range in percent terms), while Q4 and Q5 have no GROUP BY and their small deltas are within master's normal variance. The one regression, TPC-H Q7 at +12.1%, is a low-cardinality GROUP BY where the extra partitioning/coordination overhead outweighs the parallelism — worth a look but consistent with the change's tradeoff. Q15 was suppressed as within-variance but exercises the same merge path, so it is surfaced as uncertain rather than a confirmed win.

clickbench

🟢 6 improved · ⚠️ 1 inconclusive

Flagged queries (7 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 12 improvement 296 265 -10.5% <0.0001 aggregation: GROUP BY query on the exact path this PR speeds up: the final merge of per-thread single-level hash tables is now parallelized by key-hash partition, so the -10.5% is plausibly a real PR effect.
🟢 13 improvement 490 403 -17.8% <0.0001 aggregation: GROUP BY aggregation benefits directly from the new parallel single-level table merge; -17.8% is consistent with that change.
🟢 18 improvement 1418 1232 -13.1% <0.0001 aggregation: Multi-key GROUP BY (UserID, SearchPhrase) is exactly what the partitioned parallel merge accelerates; -13.1% is a plausible PR effect.
🟢 32 improvement 1460 1256 -14.0% <0.0001 aggregation: Heavy GROUP BY with many keys is the best case for parallelizing the per-thread table merge across hash partitions; -14.0% is consistent with the change.
🟢 33 improvement 1645 1198 -27.2% <0.0001 aggregation: High-cardinality GROUP BY (URL) benefits most from splitting the final merge across threads; -27.2% faster is plausibly the PR's intended effect.
🟢 34 improvement 1512 1193 -21.1% <0.0001 aggregation: Another high-cardinality GROUP BY on the parallel-merge path; -21.1% is consistent with the optimization.
⚠️ 15 not_sure 242 206 -14.9% <0.0001 aggregation: GROUP BY (SearchEngineID, SearchPhrase) runs the parallel single-level merge this PR enables by default, so the -14.9% is attributable to the diff. The measurements were noisy and it sits within master's band, so surface as not_sure rather than a firm win.

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

🔴 1 regressed

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 7 regression 556 624 +12.1% <0.0001 aggregation: This GROUP BY has low key cardinality, where the new parallel single-level merge adds partitioning/coordination overhead without payoff; the +12.1% regression is a plausible cost of the default-on change.

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.

Debug info
  • StressHouse run: 42305909-9728-405c-be27-470ea8ef2edc
  • MIRAI run: 7e408a06-5ca0-48cc-a0e6-c053157b5fda
  • PR check IDs:
    • clickbench_535338_1785165408
    • clickbench_535345_1785165408
    • clickbench_535354_1785165408
    • tpch_adapted_1_official_535374_1785165408
    • tpch_adapted_1_official_535393_1785165408
    • tpch_adapted_1_official_535407_1785165408

Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov added a commit that referenced this pull request Jul 26, 2026
Every failure in `Stateless tests (amd_tsan, flaky check)` on `b734075dd9f`
was the 180 s per-run budget, not a wrong result: `03168_query_log_privileges_not_empty`
(232 s and 199 s, passing at 94-145 s), `03008_optimize_equal_ranges`
(185 s, passing at 158 s), `01343_min_bytes_to_use_mmap_io` (182 s, passing
at 106 s) and `03735_async_insert_mergetree_count` (186 s, passing at
140-159 s). The three query-log ones failed on `SYSTEM FLUSH LOGS query_log`
hitting its own 180 s timeout while the loaded TSan server drained the log
queue.

None of them is a signal this PR can produce: all three tests it touches are
tagged `no-random-detach`, so the feature is off there and the change is the
tag line itself; `03735_async_insert_mergetree_count` is not touched by this
PR at all and fails the same way on unrelated pull requests (#110395,
#110461). Tag them the same way as `03735_async_insert_mergetree` and the
three tests tagged in `b734075dd9f`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96130&sha=b734075dd9ff4ad835fa799a594445569fc02613&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
if (params->params.max_rows_to_group_by != 0 && params->params.group_by_overflow_mode == OverflowMode::ANY)
return false;

if (!params->aggregator.canMergeSingleLevelInPartitions(*data->at(0)))

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.

enable_parallel_single_level_merge still misses several reachable single-level methods here. AggregatedDataVariants::chooseAggregationMethod returns nullable_key8 / nullable_key16 for Nullable(UInt8/UInt16), low_cardinality_key8 / low_cardinality_key16 for LowCardinality(UInt8/UInt16), and keys16 for fixed-key tuples that pack into 2 bytes, but worthParallelMergeSingleLevel only parallelizes plain key8 / key16 and this canMergeSingleLevelInPartitions check rejects the rest. So the new setting/docs still over-promise coverage: those GROUP BYs stay on the serial merge even with the setting enabled.

Please either extend one of the parallel merge paths to these variants, or narrow the setting text/tests so they explicitly say these small-key methods also remain serial.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 514/525 (97.90%) · Uncovered code

Full report · Diff report

@nihalzp

nihalzp commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

@groeneai Investigate the CI failures.

@groeneai

Copy link
Copy Markdown
Collaborator

Both remaining reds on da301c9788e6 are pre-existing trunk failures, not caused by this PR. I reproduced each one on a pristine origin/master build (1d4408f794c3) with none of your diff applied, and confirmed each is closed by its owner PR.

1. Stress test (amd_debug): Logical error: Inconsistent KeyCondition behavior (STID 5182-684a)

The failing query in the report is from 04612_reverse_key_index_analysis.sql, not from your tests:

EXPLAIN AST header = 1, projections = 1, graph = 1
SELECT count() FROM t_nan_asc WHERE (g = toUInt128(1)) AND (r = 5)
SETTINGS use_lightweight_primary_key_index_analysis = 0

That is the AST fuzzer widening g UInt32 to toUInt128(1). Reduced to two statements on a pristine master debug binary:

CREATE TABLE t_nan_asc (g UInt32, r Float64) ENGINE = MergeTree ORDER BY (g, r) SETTINGS index_granularity = 1;
INSERT INTO t_nan_asc VALUES (1, 3), (1, 5), (1, 0/0), (1, 0/0), (2, 7), (2, 0/0);
SELECT count() FROM t_nan_asc WHERE g = 1 AND r = 5 SETTINGS use_lightweight_primary_key_index_analysis = 0;              -- 1
SELECT count() FROM t_nan_asc WHERE (g = toUInt128(1)) AND (r = 5) SETTINGS use_lightweight_primary_key_index_analysis = 0; -- aborts

The first statement returns 1; the second aborts, deterministically, every run. The server log names the shape:

Inconsistent KeyCondition behavior: matchesExactContinuousRange() reported an exact continuous
range, but the mark range [0, 4) (exact subrange [1, 3)) of part all_1_1_0 is not exactly continuous.
Participating conditions: key condition (useful: true) (relaxed: false):
  (_CAST(column 0) in ['1', '1']), (column 1 in [5., 5.]), and

The abort frame is MergeTreeDataSelectExecutor.cpp:2457 in both my run and the CI stack. This is the widening-_CAST key-comparison class of #90461. Owner is #109023; on that PR's prebuilt debug binary the same two statements return 1 and 1 with zero aborts.

Breadth over the last 60 days: 292 rows across 219 distinct pull requests and 16 master runs, first seen 2026-06-15, well before this branch. Per STID: 5182-2f27 = 209 rows / 170 PRs / 11 master; 5182-684a = 63 / 57 / 5. Note #111964 is not the owner for this shape: it suppresses the check only when the in-memory index does not resolve the whole used key prefix, and here both key positions are resolved with relaxed: false, so its guard cannot fire.

2. Stress test (arm_asan_ubsan, s3): UBSan at toStartOfInterval.cpp:293

runtime error: signed integer overflow: -9223372036854775808 + -7200000000000
cannot be represented in type 'Int64'

One statement on a pristine master ASan+UBSan build, no table and no settings:

SELECT toStartOfInterval(
    reinterpret(toInt64(-9223372036854775808), 'DateTime64(9, \'Europe/Berlin\')'),
    toIntervalHour(2),
    reinterpret(toInt64(-9223372036854775808), 'DateTime64(9, \'Europe/Berlin\')'));

That gives the same file, line and column as the CI report, toStartOfInterval.cpp:293:80: runtime error: signed integer overflow (my addend is -3600000000000 rather than the report's -7200000000000; that term is just the time zone offset the fuzzer happened to hit, the overflowing addition is the same one). It is the three-argument origin overload adding the rounding offset back to the origin without an overflow check; in a time zone east of UTC the offset is negative, so an origin near the lower bound of Int64 wraps. A UTC origin has a zero offset and is unaffected, which is why it only fires for some time zones.

Owner is #112045, which adds a common::addOverflow check at exactly that line. On its prebuilt ASan+UBSan binary the same statement raises Code: 407 ... does not fit into Int64 with zero UBSan reports.

Breadth over the last 60 days: 58 rows across 49 distinct pull requests and 7 master runs, first seen 2026-06-29.

Neither is reachable from your diff. Your 18 changed files are the aggregator, the aggregating transform and plan step, settings and your two new tests; nothing under src/Storages/MergeTree/ or src/Functions/. Both reds come from the stress run's fuzzed queries against unrelated code.

One thing on this PR that is worth your attention

04507_parallel_single_level_merge_group_by_limit failed once on head 80d5206008c5 in Stateless tests (amd_debug, flaky check):

The query succeeded but the server error '158' was expected (query:
SELECT count() FROM (SELECT intDiv(number, 200) AS g, count() AS c FROM numbers_mt(300000) GROUP BY g)
SETTINGS max_rows_to_group_by = 1000, group_by_overflow_mode = 'throw')

1 failure in 100 runs, and the same 1-in-100 on the earlier head 4006706f72e4. That was the old form of the test, where the throw depended on how many streams the scheduler fed. The rewrite on da301c9788e6 (8000 distinct keys, limit 4000, plus SET optimize_aggregation_in_order = 0) is 100/100 clean on the flaky check across all four sanitizer flavours, and 04506 is clean too. So it looks addressed; I mention it only because it is the one row on this PR that was actually yours, in case you want to keep an eye on it after the next rebase.

For the two stress reds, no action is needed on your side. Merging master once #112045 and #109023 land will clear them.

@nihalzp
nihalzp added this pull request to the merge queue Jul 27, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 27, 2026
@nihalzp
nihalzp added this pull request to the merge queue Jul 27, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 27, 2026
@nihalzp
nihalzp added this pull request to the merge queue Jul 28, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 28, 2026
@nihalzp

nihalzp commented Jul 28, 2026

Copy link
Copy Markdown
Member Author

@groeneai Why style check is falling in merge queue?

@groeneai

Copy link
Copy Markdown
Collaborator

It is not your diff and not a style violation. Only 1 of the 13 Style sub-checks fails, settings_changes_history:

src/Core/SettingsChangesHistory.cpp changed but its diff could not be fetched to validate the settings
history (the check must not be skipped when the file changed). Error: no data recorded by the
store_data.py workflow hook.

Root cause is a praktika bug in merge-queue event detection. ci/praktika/info.py:133 is return self.env.EVENT_TYPE == "merge_group", but EVENT_TYPE is only ever assigned from praktika's own enum and ci/praktika/workflow.py:16 defines MERGE_QUEUE = "merge_queue". GitHub's event name is merge_group, praktika's enum value is merge_queue, so Info().is_merge_queue_event is False in every real merge-queue run. Your run's config_workflow/job.log dumps EVENT_TYPE='merge_queue', PR_NUMBER=0, LINKED_PR_NUMBER=110395, WORKFLOW_NAME='MergeQueueCI'.

Consequence: store_data.py:96-98 gates the settings-history half of the hook on info.pr_number or info.is_merge_queue_event, which is False in the queue, so settings_history_changed_settings is never recorded (the stored keys in your run are exactly ['changed_files', 'build_digest', 'master_commits']). check_style.py:596-616 then sees the file in changed_files, finds nothing recorded, and fails fail-closed. The check is correct; the hook silently skipped its second half.

It is deterministic and unrelated to your change: the same single red on all three of your merge-queue refs (pr-110395-4a44dcef @ 999b2e18, pr-110395-d11bc66e @ 2cf27696, pr-110395-fdd6d554 @ bb50a149), plus 2 more on #111573, the only other merge-queue entry that touched that file since the check landed in #111605 on 2026-07-27. The 36 merge-queue runs recorded OK cover 35 PRs, none of which touched SettingsChangesHistory.cpp, so they all took the path not in changed_files early return. In the merge queue this validator has passed only where it had nothing to validate, and failed on every entry that actually touched the file.

Your entry itself is fine: enable_parallel_single_level_merge is added under the 26.8 block, which matches VERSION_MAJOR 26 / VERSION_MINOR 8 in cmake/autogenerated_versions.txt, so the check passes as soon as the hook records the diff.

A fix task is open on my side and I will post the fixing-PR link here when it opens. One caveat worth stating: fixing the predicate makes the settings-history validator actually run in the merge queue for the first time, so unrelated merge-queue entries touching that file may start showing genuine reds.

@nihalzp

nihalzp commented Jul 28, 2026

Copy link
Copy Markdown
Member Author

@groeneai Create a PR fixing the issue.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I am opening a PR that fixes is_merge_queue_event in ci/praktika/info.py (compare against the Workflow.Event.MERGE_QUEUE enum value rather than GitHub's event name merge_group), adds a regression test that patches _Environment.EVENT_TYPE instead of mocking the predicate, and makes store_data.py actually record settings_history_fetch_error so a real fetch failure reports its cause instead of the generic message you saw.

I will post the link here.

@groeneai

Copy link
Copy Markdown
Collaborator

@nihalzp the fix is open: #112227

It ships two of the three things I listed above:

  1. is_merge_queue_event now compares EVENT_TYPE against Workflow.Event.MERGE_QUEUE instead of
    GitHub's event name merge_group, so the value and the event name cannot drift apart again.
  2. A regression test that drives a real merge_group payload through _Environment.from_env() into
    the real property, rather than mocking the predicate the way the existing merge-queue tests in
    ci/tests/test_gh.py do (which is why they never caught this).

The third item, making a real diff-fetch failure report its cause instead of the generic "no data
recorded" text, is deliberately not in that PR. Reviewing it turned up a separate root cause:
the fetch uses Shell.get_output, which returns stdout even when the command exits non-zero, so an
auth or 5xx failure currently surfaces as the empty patch error. Simply storing that exception
would record an authoritative-looking but wrong reason. Fixing it properly means routing the fetch
through the retrying, error-preserving helper, which is a different change from this one-line
predicate fix, so it is tracked separately and will get its own PR rather than being folded in here.

Your PR needs no change. Once #112227 merges, the merge-queue run records the settings-history diff
and settings_changes_history validates your 26.8 entry, which is already correct.

@nihalzp
nihalzp added this pull request to the merge queue Jul 28, 2026
Merged via the queue into ClickHouse:master with commit 0f33598 Jul 28, 2026
351 of 353 checks passed
@nihalzp
nihalzp deleted the parallel-single-level-merge branch July 28, 2026 09:34
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

Following up on the third item from #110395 (comment): it is now open as #112970.

It routes the settings-history diff fetch through GH.get_output_with_retries with a new opt-in strict parameter, so a transient 5xx is retried instead of being fatal and a real failure raises a diagnostic naming the command, its exit code, the attempts made and its stderr, rather than being laundered into an empty string that the next check relabelled as GitHub's large-diff case. That reason is then stored in settings_history_fetch_error, which had a reader in check_style.py and no writer, so the report you saw said "no data recorded".

Nothing is needed on your side; #112227 already unblocked this PR.

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 26, 2026
…the new join algorithm from ClickHouse#109005

- tests/clickhouse-test: randomize `allow_distinct_partitions_independently`,
  `force_distinct_partitions_independently`,
  `max_number_of_partitions_for_independent_distinct` and
  `enable_parallel_single_level_merge`. `force_*` is conditional on `allow_*`,
  because forcing is a no-op when the optimization is not allowed.
- ci/jobs/scripts/stress/stress.py: add `parallel_full_sorting_merge` to the
  `join_algorithm` rotation (skipped in Upgrade check, because the previous
  release may not know this value).
- BuzzHouse: add the four new settings next to their aggregate analogs.

Related: ClickHouse#109005
Related: ClickHouse#108326
Related: ClickHouse#110395

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants