Skip to content

Optimize aggregations of LowCardinality of 128 and 256 bit integers - #114982

Draft
bobrik wants to merge 7 commits into
ClickHouse:masterfrom
bobrik:ivan/lc-aggregation-speedup
Draft

bobrik wants to merge 7 commits into
ClickHouse:masterfrom
bobrik:ivan/lc-aggregation-speedup

Conversation

@bobrik

@bobrik bobrik commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

This is simply expanding what is done for narrower integers to wider ones.

Comparing column_low_cardinality_key_holder to the previous commit:

Key type Encoding Before CPU time After CPU time Reduction Speedup
UInt8 Plain 320,240 ns 321,169 ns -0.3% 1.00x
UInt8 LC 1,366,296 ns 1,369,728 ns -0.3% 1.00x
UInt16 Plain 320,863 ns 322,198 ns -0.4% 1.00x
UInt16 LC 1,391,415 ns 1,377,083 ns 1.0% 1.01x
UInt32 Plain 320,757 ns 321,323 ns -0.2% 1.00x
UInt32 LC 1,388,380 ns 1,385,711 ns 0.2% 1.00x
UInt64 Plain 326,842 ns 325,383 ns 0.4% 1.00x
UInt64 LC 1,381,219 ns 1,440,143 ns -4.3% 0.96x
UInt128 Plain 1,012,926 ns 911,887 ns 10.0% 1.11x
UInt128 LC 8,019,216 ns 1,452,770 ns 81.9% 5.52x
UInt256 Plain 8,149,345 ns 8,132,693 ns 0.2% 1.00x
UInt256 LC 11,576,753 ns 1,498,433 ns 87.1% 7.73x

For end-to-end benchmark in group_by_integer_key_width.xml:

Grouping key Before median After median Reduction Speedup
LowCardinality(UInt64) 2.0680 s 2.1344 s -3.2% 0.97x
UInt64 0.6938 s 0.6905 s 0.5% 1.00x
LowCardinality(UInt128) 2.8588 s 2.5819 s 9.7% 1.11x
UInt128 1.0269 s 1.0140 s 1.3% 1.01x
LowCardinality(UInt256) 3.3996 s 2.9630 s 12.8% 1.15x
UInt256 1.7643 s 1.6781 s 4.9% 1.05x

There's ~5% noise level if you look at the unaffected paths.

There's now also a test to ensure that the right aggregation is used.

Changelog category (leave one):

  • Performance Improvement

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

Optimize aggregations of LowCardinality of 128 and 256 bit integers.


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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [525e442]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-26fa) FAIL cidb

AI Review

Summary

This PR reroutes single-key LowCardinality(UInt128) / LowCardinality(UInt256) GROUP BY from the packed-key path to HashMethodSingleLowCardinalityColumn, adds raw-index and sparse-dictionary optimizations, and extends coverage with benchmarks and a focused functional test. I found one remaining performance gap: the new one-time index-width dispatch is only wired into the baseline / merge / selector paths, while the default adaptive frozen path still uses the old uncached index-reading loop.

Findings
  • ⚠️ Majors
    • [src/Interpreters/Aggregator.cpp:1122] The new dispatchLowCardinalityDictionaryCache call does not cover the adaptive frozen kernels. executeFrozenImpl in src/Interpreters/AdaptiveAggregationKernels.cpp still constructs LocalMethod::StateNoCache and loops on getKeyHolder directly, so once a wide shared LowCardinality query freezes it never reaches UncachedUInt32State. For dictionaries above the new 32 MiB cutoff, the PR's latest fast path therefore does not apply to one of the main GROUP BY execution modes.
    • Suggested fix: route the adaptive frozen kernels through the same dispatch helper, or add an equivalent typed-index specialization there, and add a focused adaptive perf case for a wide shared dictionary that takes the uncached path.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: wire the wide LowCardinality dispatch into the adaptive frozen aggregation path as well, or otherwise show with focused measurements that the default adaptive mode is not left on the old uncached index-width loop.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 188/238 (78.99%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 35 queries analysed

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

This PR adds dedicated wide-integer (UInt128/UInt256) LowCardinality GROUP BY aggregation methods plus a raw-index fast path and cache-size guard; the merge and two-level refactors are behavior-preserving for existing narrow and string LowCardinality keys. Standard ClickBench and TPC-H queries do not group by wide LowCardinality integer keys, so none exercise the changed hot path — every directional flag was downgraded as thin-base variance, most of it landing inside master's current variance bands. The dramatic TPC-H results (×20.5 and ×6.9 faster) come from a 2-config base that captured slow master runs, not a real speedup, and the +60.0% TPC-H Q17 swing is on extremely noisy measurements. The two borderline ClickBench aggregations (Q28, Q32) remain not_sure; there is no credible regression attributable to this change.

clickbench

⚠️ 11 inconclusive

Flagged queries (11 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 277 185 -33.2% <0.0001 This PR only changes wide-integer (UInt128/UInt256) LowCardinality GROUP BY aggregation, which this query doesn't exercise; the -33.2% is within-band, thin-base variance, not a PR effect.
⚠️ 5 not_sure 368 234 -36.4% <0.0001 Off the changed path — the PR touches wide LowCardinality integer aggregation only. The -36.4% reflects run-to-run variance against a 2-config base.
⚠️ 9 not_sure 340 381 +12.1% <0.0001 Both source and base sit inside master's variance band [282.5,430.5], and the query doesn't use wide LowCardinality integer keys, so the +12.1% is noise rather than a real regression.
⚠️ 13 not_sure 422 346 -17.9% <0.0001 The PR's changed hot path (wide LowCardinality integer GROUP BY) isn't exercised here; the -17.9% is thin-base run-to-run variance.
⚠️ 15 not_sure 223 160 -28.3% <0.0001 Query history is intrinsically flaky and the PR doesn't touch this path, so the -28.3% is noise, not a PR-driven improvement.
⚠️ 16 not_sure 760 614 -19.3% <0.0001 Unrelated to this PR, which only alters wide LowCardinality integer aggregation; the -19.3% is thin-base variance.
⚠️ 17 not_sure 541 246 ×2.2 faster <0.0001 The ×2.2 faster result is large but off-path — this query doesn't group by wide LowCardinality integer keys, so it cannot be attributed to this PR and reads as thin-base variance.
⚠️ 18 not_sure 1226 1090 -11.1% <0.0001 Off the changed aggregation path; the -11.1% on a noisy, thin base is run-to-run variance.
⚠️ 28 not_sure 1022 1094 +7.0% <0.0001 aggregation: Borderline with mixed signals from the two tests and noisy underlying measurements; unrelated to the wide LowCardinality integer path this PR changes.
⚠️ 31 not_sure 362 320 -11.6% <0.0001 Not on the changed code path; the -11.6% is thin-base variance rather than a PR improvement.
⚠️ 32 not_sure 1287 1370 +6.4% 0.0008 aggregation: Borderline and noisy; off the wide LowCardinality integer aggregation path this PR modifies.

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

⚠️ 4 inconclusive

Flagged queries (4 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 1044 51 ×20.5 faster <0.0001 The ×20.5 faster result sits inside an enormous master variance band [42,1044] and doesn't touch the wide LowCardinality integer aggregation this PR changes; the 2-config base simply caught slow master runs.
⚠️ 7 not_sure 554 80 ×6.9 faster <0.0001 The ×6.9 faster delta is a wide-band, thin-base artifact and off the PR's changed path, not a real improvement.
⚠️ 8 not_sure 163 88 -46.0% <0.0001 Off-path for this PR; the -46.0% is within master's wide variance band [77,163] against a 2-config base.
⚠️ 17 not_sure 65 104 +60.0% <0.0001 The underlying measurements are extremely noisy and both medians fall inside band [64,109]; this query doesn't exercise the changed path, so the +60.0% is variance, not a regression.

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: 1cd77bc8-b60d-4a40-aa68-7489ef88dce6
  • MIRAI run: b795b396-bfaa-4423-aab8-56b82599e675
  • PR check IDs:
    • clickbench_57020_1787862259
    • clickbench_57026_1787862260
    • clickbench_57038_1787862259
    • tpch_adapted_1_official_57049_1787862259
    • tpch_adapted_1_official_57063_1787862259
    • tpch_adapted_1_official_57090_1787862259

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 525e442e4 with master 3eb72756a (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
Binary Master PR Δ
programs/clickhouse-stripped 711.97 MiB 710.14 MiB -1.83 MiB (-0.26%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

16 object files changed (+3.04 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 20.33 MiB 23.07 MiB +2.75 MiB (+13.52%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregationKernels.cpp.o 1.82 MiB 1.93 MiB +103.98 KiB (+5.57%)
src/CMakeFiles/dbms.dir/Processors/Transforms/LimitByTransform.cpp.o 1.16 MiB 1.23 MiB +75.23 KiB (+6.33%)
src/CMakeFiles/dbms.dir/Processors/Transforms/NegativeLimitByTransform.cpp.o 893.45 KiB 949.22 KiB +55.77 KiB (+6.24%)
src/CMakeFiles/dbms.dir/Interpreters/AggregatedDataVariants.cpp.o 724.85 KiB 751.69 KiB +26.84 KiB (+3.70%)
src/CMakeFiles/dbms.dir/Interpreters/AggregationMethod.cpp.o 422.50 KiB 441.55 KiB +19.05 KiB (+4.51%)

737 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

127 translation units recompiled, 1368 s compile time in total, 127 of them have a recent master baseline.

Job report

@bobrik

bobrik commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

For this query:

SELECT count()
FROM
(
    SELECT
        stackMap.stack AS stack,
        sum(stackMap.value) AS value
    FROM r0.profiles_v4_replica
    ARRAY JOIN stackMap
    WHERE
        (profileType = 'process_cpu:cpu:nanoseconds:cpu:nanoseconds')
        AND (serviceName = 'ebpf.profiler')
        AND (label_app_name = 'fl2.service')
        AND (timestamp >= '2026-08-18 00:00:00') and timestamp < '2026-08-19 00:00:00'
    GROUP BY stack
    ORDER BY value ASC
)
SETTINGS max_threads = 1

Before:

1 row in set. Elapsed: 233.416 sec. Processed 934.64 thousand rows, 37.37 GB (4.00 thousand rows/s., 160.11 MB/s.)
image

After:

1 row in set. Elapsed: 223.896 sec. Processed 934.64 thousand rows, 37.37 GB (4.17 thousand rows/s., 166.92 MB/s.)
image

In absolute terms DB::AggregatingTransform::consume sampled CPU decreased 75.37s -> 65.26s (-13.4%).

@bobrik
bobrik force-pushed the ivan/lc-aggregation-speedup branch from 994cdaf to 9a3c36d Compare August 19, 2026 06:09
Comment on lines +392 to +395
if (size_of_field == 16)
return Type::low_cardinality_key128;
if (size_of_field == 32)
return Type::low_cardinality_key256;

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.

These new returns change LowCardinality(Nullable(UInt128)) / LowCardinality(Nullable(UInt256)) from the old nullable_serialized path to low_cardinality_key128 / low_cardinality_key256. That loses an existing external-aggregation safeguard: Aggregator::mergeBlocks upgrades nullable_serialized to nullable_serialized_hash64, but it has no corresponding *_hash64 remap for any low-cardinality numeric method (see src/Interpreters/Aggregator.cpp, around the APPLY_FOR_VARIANTS_THAT_MAY_USE_BETTER_HASH_FUNCTION block).

So once max_bytes_before_external_group_by spills, wide nullable LC keys now fall back to the CRC32-backed map in the merge stage, which is exactly the path the merge-side comment says needs a stronger hash for very large key counts. Please either add *_hash64 counterparts/remapping for these methods, or keep the nullable 128/256 LC path on nullable_serialized until the external-merge case is covered.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

cc @nickitat for thoughts based on #114210, which made me rebase and tickle the bot about this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I received the same remark from AI review; I think we can assume that low cardinality actually means low cardinality and 32-bit hash is enough.

@bobrik

bobrik commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Wrong issue comment

@bobrik
bobrik force-pushed the ivan/lc-aggregation-speedup branch from 9a3c36d to 34fce08 Compare August 20, 2026 23:24
@bobrik

bobrik commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

I added another commit, which gives (on top of the previous one):

  • LC UInt128 key holder: 10.9% faster.
  • LC UInt256 key holder: 13.5% faster.
  • Narrow LC keys: neutral.
  • End-to-end LC UInt128 aggregation: 2.5910 -> 2.5093 seconds, 3.15% faster.

@bobrik
bobrik force-pushed the ivan/lc-aggregation-speedup branch from dabb32b to 1f5ed40 Compare August 22, 2026 01:17
@bobrik

bobrik commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

Some numbers from the latest iteration in a sister PR: #114993 (comment).

@bobrik
bobrik force-pushed the ivan/lc-aggregation-speedup branch from 1f5ed40 to defce26 Compare August 27, 2026 00:04
@bobrik

bobrik commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Same as with #114993 and #115925, this too conflicted with #96630. cc @thevar1able

@bobrik
bobrik force-pushed the ivan/lc-aggregation-speedup branch from defce26 to 80006c9 Compare August 27, 2026 05:22
@bobrik

bobrik commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Updated to not balloon Aggregator.cpp compilation as much, while preserving the wins.

bobrik added 6 commits August 26, 2026 23:14
This is simply expanding what is done for narrower integers to wider ones.

Comparing `column_low_cardinality_key_holder` to the previous commit:

| Key type  | Encoding | Before CPU time | After CPU time | Reduction | Speedup |
|-----------|----------|----------------:|---------------:|----------:|--------:|
| `UInt8`   | Plain    |      320,240 ns |     321,169 ns |     -0.3% |   1.00x |
| `UInt8`   | LC       |    1,366,296 ns |   1,369,728 ns |     -0.3% |   1.00x |
| `UInt16`  | Plain    |      320,863 ns |     322,198 ns |     -0.4% |   1.00x |
| `UInt16`  | LC       |    1,391,415 ns |   1,377,083 ns |      1.0% |   1.01x |
| `UInt32`  | Plain    |      320,757 ns |     321,323 ns |     -0.2% |   1.00x |
| `UInt32`  | LC       |    1,388,380 ns |   1,385,711 ns |      0.2% |   1.00x |
| `UInt64`  | Plain    |      326,842 ns |     325,383 ns |      0.4% |   1.00x |
| `UInt64`  | LC       |    1,381,219 ns |   1,440,143 ns |     -4.3% |   0.96x |
| `UInt128` | Plain    |    1,012,926 ns |     911,887 ns |     10.0% |   1.11x |
| `UInt128` | LC       |    8,019,216 ns |   1,452,770 ns |     81.9% |   5.52x |
| `UInt256` | Plain    |    8,149,345 ns |   8,132,693 ns |      0.2% |   1.00x |
| `UInt256` | LC       |   11,576,753 ns |   1,498,433 ns |     87.1% |   7.73x |

For end-to-end benchmark in `group_by_integer_key_width.xml`:

| Grouping key                  | Before median | After median | Reduction | Speedup |
|-------------------------------|--------------:|-------------:|----------:|--------:|
| `LowCardinality(UInt64)`      |      2.0680 s |     2.1344 s |     -3.2% |   0.97x |
| `UInt64`                      |      0.6938 s |     0.6905 s |      0.5% |   1.00x |
| `LowCardinality(UInt128)`     |      2.8588 s |     2.5819 s |      9.7% |   1.11x |
| `UInt128`                     |      1.0269 s |     1.0140 s |      1.3% |   1.01x |
| `LowCardinality(UInt256)`     |      3.3996 s |     2.9630 s |     12.8% |   1.15x |
| `UInt256`                     |      1.7643 s |     1.6781 s |      4.9% |   1.05x |

There's ~5% noise level if you look at the unaffected paths.

There's now also a test to ensure that the right aggregation is used.
For UInt128 and UInt256 dictionary keys, cache the raw index-data pointer
when the aggregation state is constructed. `getIndexAt` then reads
the UInt8/UInt16/UInt32/UInt64 index directly with unalignedLoad
avoiding repeated `IColumn` -> `ColumnVector` -> `PODArray` access.

After decoding an index, emplaceKey and findKey pass that dictionary
position directly to the base method. Previously, cache misses called
getKeyHolder, which decoded the same index a second time.

The raw-pointer path is compile-time restricted to wide numeric keys.
Narrow numeric and string keys retain the original implementation because
the unrestricted version regressed their microbenchmarks by 5–8%.

Results:

* LC UInt128 key holder: 10.9% faster.
* LC UInt256 key holder: 13.5% faster.
* Narrow LC keys: neutral.
* End-to-end LC UInt128 aggregation: 2.5910 -> 2.5093 seconds, 3.15% faster.
Compare the single-column LowCardinality aggregation method with the
packed-key method for shared UInt128 and UInt256 dictionaries. Sweep
dictionary size and active cardinality to identify where full-dictionary
mapped and visit caches stop paying for themselves.

Extend the SQL performance test with sparse shared-dictionary aggregation
using one and eight workers to cover end-to-end latency and memory scaling.
HashMethodSingleLowCardinalityColumn allocates about 9 bytes per
dictionary entry for its mapped and visit caches. For sparse wide
dictionaries, this can consume tens of MiB per aggregation state.

Limit these caches to 32 MiB for UInt128 and UInt256 keys. For larger
dictionaries, hash values directly without initializing the dense caches
or the shared-dictionary hash.

Dispatch between cached and uncached implementations once per hashing
state to avoid adding a branch to the per-row aggregation path. Extend
the benchmark to report which path is selected.
Add focused benchmarks for `getIndexAt` across all index widths and for
processing large shared dictionaries through one or 64 independent
aggregation states.

Cover sparse and dense active dictionaries for `UInt128` and `UInt256`,
and report index width, state count, dictionary size, and cache usage.
`HashMethodSingleLowCardinalityColumn::getIndexAt` selected the index
width for every processed row. Dispatch `UInt8`, `UInt16`, `UInt32`, or
`UInt64` once per hashing state alongside the dictionary-cache decision.

Update `ReadSharedDictionaryIndexes` to measure the dispatched typed
reader. Standalone index reads remained flat because the simple loop was
already unswitched by the compiler.

For 64 aggregation states with a large uncached dictionary, the
`UInt128` benchmark moved from 68.64 to 58.62 ms, or 14.6% faster. The
`UInt256` benchmark moved from 95.38 to 80.38 ms, or 15.7% faster.

`group_by_integer_key_width` remained neutral for wide keys, within -1.3%
to +1.1%, while `LowCardinality(UInt64)` improved by 5.8%.
@bobrik
bobrik force-pushed the ivan/lc-aggregation-speedup branch from 80006c9 to 525e442 Compare August 27, 2026 06:14
all_keys_are_const,
overflow_row);
};
ColumnsHashing::dispatchLowCardinalityDictionaryCache(state, execute);

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.

The new dispatchLowCardinalityDictionaryCache wiring here only covers the baseline / merge / bucket-selector loops. The default adaptive frozen path still constructs typename LocalMethod::StateNoCache and then drives it directly through getKeyHolder in src/Interpreters/AdaptiveAggregationKernels.cpp (for example at lines 352, 433, 527, and 594), so once a wide shared LowCardinality(UInt128/UInt256) aggregation freezes it never reaches UncachedUInt32State.

That leaves large dictionaries above the 32 MiB cache cutoff on the old per-row size_of_index_type dispatch for the rest of the query, which means this PR's last optimization does not apply to one of the main GROUP BY execution modes. Please route the adaptive frozen kernels through the same helper, or add an equivalent typed-index dispatch there, and cover it with a focused adaptive perf case.

@bobrik

bobrik commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

This PR can be whittled down quite a bit if we land #115925 first. I'm marking it as draft for now.

@bobrik
bobrik marked this pull request as draft August 28, 2026 22:37
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 4, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants