Skip to content

Reuse LowCardinality aggregation mappings across blocks - #114993

Draft
bobrik wants to merge 2 commits into
ClickHouse:masterfrom
bobrik:ivan/single-dict-aggregator
Draft

bobrik wants to merge 2 commits into
ClickHouse:masterfrom
bobrik:ivan/single-dict-aggregator

Conversation

@bobrik

@bobrik bobrik commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Previously dictionary position to aggregate state mappings were only valid within a block. For parts where there's only a single dictionary, this is too restrictive and resulted in repeated work.

This moves the mapping cache to the aggregation method, matching its lifetime to the aggregation hash table. We keep the successful mappings while the dict remains unchanged. Non-shared dictionaries remain block local.

This gives a very nice speedup to the benchmark in the previous commit:

Width LC before LC after Change
UInt8 0.1220 s 0.1158 s -5.1%
UInt16 0.1703 s 0.1395 s -18.1%
UInt32 0.1884 s 0.1489 s -20.9%
UInt64 0.1952 s 0.1513 s -22.5%
UInt128 0.5676 s 0.5649 s -0.5%
UInt256 0.9354 s 0.9206 s -1.6%
String (6 B) 0.2535 s 0.1598 s -37.0%
String (26 B) 0.2521 s 0.1630 s -35.4%
String (56 B) 0.2689 s 0.1655 s -38.5%

The improvements for UInt128 and UInt256 will be there after #114982 is merged.

The benefit is largest when many blocks share the same dictionary, because dictionary-position mappings are reused across those blocks.

AI assisted, scratching an itch I've had for a while.

Changelog category (leave one):

  • Performance Improvement

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

Improve aggregation performance by reusing LowCardinality aggregation mappings across blocks.


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

@yariks5s yariks5s 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 [af50e9d]

Summary: ✅


AI Review

Summary

This PR moves single-column LowCardinality aggregation mapping reuse from per-block state to the aggregation method lifetime, and clears that cache on the paths where the hash table stops being authoritative (convertToTwoLevel, spill/output conversion, merge preparation, and adaptive freeze). The current head also addresses the earlier correctness and memory/performance gaps around inline count(), UInt8, bucket-parallel merge, and stale cache invalidation, and I did not find a remaining blocker or major issue in the changed code.

Final Verdict

✅ No new blocking findings.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 16, 2026
Comment thread src/Common/ColumnsHashing.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 35 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 reworks single-column LowCardinality GROUP BY aggregation (adding a cross-block dictionary-position cache) and re-enables the inline COUNT optimization for LowCardinality keys. Only clickbench Q13, a single-column string GROUP BY, sits on that path, and its -18.6% improvement is consistent with the change. Every other flag falls outside the code this PR touches: all four tpch_adapted_1_official queries (join/subquery, no LowCardinality), clickbench Q4/Q5 (COUNT DISTINCT with no GROUP BY), and the numeric or multi-key GROUP BYs Q15-Q18/Q30/Q31. These coincide with 2-build baselines whose medians sit at the edges of the known master variance, so they are downgraded to not-sure rather than credited to the PR.

clickbench

🟢 1 improved · ⚠️ 8 inconclusive

Flagged queries (9 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 13 improvement 422 343 -18.6% <0.0001 aggregation: Single-column GROUP BY on a string key is exactly the path this PR optimizes with a cross-block LowCardinality dictionary-position cache; -18.6% is consistent, though the 2-build baseline is thin.
⚠️ 4 not_sure 277 185 -33.2% <0.0001 COUNT(DISTINCT) with no GROUP BY doesn't use the single-LowCardinality-column aggregation path this PR changes, and the base median (277 ms) sits above the current master band [93,220], so this reads as thin-baseline sampling.
⚠️ 5 not_sure 368 251 -31.8% <0.0001 Another COUNT(DISTINCT) without GROUP BY, outside this PR's LowCardinality group-by path; the base median also sits above the master band [131,292], so the delta looks like baseline variance.
⚠️ 15 not_sure 223 163 -26.9% <0.0001 aggregation: Groups by a numeric UserID key, not a LowCardinality column, so this PR's changes don't apply; with a flaky history this delta reads as run-to-run variance.
⚠️ 16 not_sure 760 595 -21.7% <0.0001 aggregation: Multi-key GROUP BY uses a composite-key method, not the single-LowCardinality-column path this PR touches, so this delta is unrelated to the change.
⚠️ 17 not_sure 541 239 ×2.3 faster <0.0001 aggregation: Multi-key GROUP BY, outside this PR's single-LowCardinality-column path; a ×2.3 faster swing on a thin baseline is not plausibly caused by this change.
⚠️ 18 not_sure 1226 1032 -15.8% <0.0001 aggregation: Three-key GROUP BY, not the single-LowCardinality-column path this PR optimizes; treat as baseline variance.
⚠️ 30 not_sure 266 228 -14.3% <0.0001 aggregation: Multi-key GROUP BY, outside the single-LowCardinality-column path this PR changes; the delta is run-to-run variance.
⚠️ 31 not_sure 362 305 -15.7% <0.0001 aggregation: Multi-key GROUP BY, not the single-LowCardinality-column path this PR touches, so this delta is baseline variance rather than a PR effect.

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 join_operator: TPC-H has no LowCardinality columns, so this aggregation-cache PR cannot produce a ×20.5 faster shift; the base median equals the top of the master band [42,1044], a classic thin-baseline outlier.
⚠️ 7 not_sure 554 79 ×7.0 faster <0.0001 join_operator: TPC-H join query outside this PR's LowCardinality aggregation path; the base median sits at the top of the master band [67,554], so ×7.0 faster is a baseline artifact.
⚠️ 8 not_sure 163 88 -46.0% <0.0001 join_operator: TPC-H query with no LowCardinality columns; the base median at the band top [77,163] makes -46.0% a thin-baseline artifact, not a PR effect.
⚠️ 17 not_sure 65 105 +61.5% <0.0001 TPC-H correlated subquery unrelated to this PR's LowCardinality aggregation change; the measurements were very noisy and the base landed at the band floor, so the +61.5% regression is not real.

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: 7f12e890-2ec4-4df6-89f3-b8a61bcffc60
  • MIRAI run: 5872ab42-31eb-4bf5-a37c-76884823c98a
  • PR check IDs:
    • clickbench_62854_1787863748
    • clickbench_62883_1787863750
    • clickbench_63058_1787863756
    • tpch_adapted_1_official_63160_1787863762
    • tpch_adapted_1_official_63261_1787863771
    • tpch_adapted_1_official_63363_1787863785

@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from 6039e7e to 574d449 Compare August 16, 2026 16:18
@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from 574d449 to 05b4641 Compare August 16, 2026 18:04
Comment thread src/Interpreters/Aggregator.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d643c5296 with master 9d8eed34c (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 709.32 MiB -2.64 MiB (-0.37%)

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 ⚠️

10 object files changed (+1.23 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 20.33 MiB 21.49 MiB +1.17 MiB (+5.74%)
src/CMakeFiles/dbms.dir/Interpreters/AggregatedDataVariants.cpp.o 724.85 KiB 748.06 KiB +23.21 KiB (+3.20%)

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

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +359.1 s (+8%) in total before that adjustment.

Job report

@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch 3 times, most recently from 00a0bb7 to 18372f3 Compare August 17, 2026 21:30
Comment thread src/Interpreters/AggregationMethod.h Resolved
@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from 18372f3 to 9b063a7 Compare August 17, 2026 23:07
@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from 9b063a7 to 0b84416 Compare August 18, 2026 00:03
Comment thread src/Interpreters/AggregationMethod.h Resolved
@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch 2 times, most recently from 00c1345 to 0f39714 Compare August 18, 2026 03:29
@bobrik

bobrik commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

It's doing worse than expected 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

My dictionaries are yuge:

# du -msc /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_*/stackMap%2Estack.dict.bin
1011    /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_0_14178_8/stackMap%2Estack.dict.bin
495     /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_14179_16995_5/stackMap%2Estack.dict.bin
478     /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_16996_19682_5/stackMap%2Estack.dict.bin
458     /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_19683_22232_5/stackMap%2Estack.dict.bin
436     /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_22233_24765_6/stackMap%2Estack.dict.bin
199     /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_24766_25317_4/stackMap%2Estack.dict.bin
190     /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_25318_25837_5/stackMap%2Estack.dict.bin
42      /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_25838_25867_2/stackMap%2Estack.dict.bin
39      /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_25868_25899_2/stackMap%2Estack.dict.bin
18      /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_25900_25905_1/stackMap%2Estack.dict.bin
14      /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_25906_25911_1/stackMap%2Estack.dict.bin
8       /state/clickhouse/continuous-profiling/data/r0/profiles_v4_replica/20260818_25912_25917_1/stackMap%2Estack.dict.bin
3383    total

That's about 66 million entries in the biggest one if my math is right.

  • 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

There's a bunch of gains coming from aggregations in #114982 (see #114982 (comment)).

Here:

  • ColumnLowCardinality::insertRangeFrom: 130s -> 127s, only −2.31%.
  • mapUniqueIndex: 68.263s -> 44.158s, −35.3%.
  • Old UInt128 gather: 11.632s → 0s.
  • Old dictionary insertion: 48.053s.
  • New uniqueInsertRangeFromDictionary: 80.632s (!!).

I'll see what can be done about this.

@bobrik

bobrik commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

Using the same query as above, but with v3 improvements from #114870:

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: 234.376 sec. Processed 934.64 thousand rows, 37.37 GB (3.99 thousand rows/s., 159.45 MB/s.)
1 row in set. Elapsed: 239.662 sec. Processed 934.64 thousand rows, 37.37 GB (3.90 thousand rows/s., 155.94 MB/s.)
image
  • After:
1 row in set. Elapsed: 224.554 sec. Processed 934.64 thousand rows, 37.37 GB (4.16 thousand rows/s., 166.43 MB/s.)
1 row in set. Elapsed: 222.283 sec. Processed 934.64 thousand rows, 37.37 GB (4.20 thousand rows/s., 168.13 MB/s.)
image

That's pretty much the same as before. Good but not great.

@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch 3 times, most recently from b96fce6 to c0285ce Compare August 20, 2026 21:37
@bobrik

bobrik commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

Added a benchmark and an optimization for Array(LowCardinality(T)) via ColumnArray::cut:

  • ARRAY JOIN: 0.867386s -> 0.700599s (-19.2%)
  • Flat control: 0.556328s -> 0.558791s (+0.4%, noise)
  • Relative ARRAY JOIN overhead: 55.9% -> 25.4%

@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from c0285ce to 913aa4f Compare August 20, 2026 22:31
@bobrik

bobrik commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

Updates to v4 in #114870 + latest #114982 + updates here helped quite a bit.

Same 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: 237.789 sec. Processed 934.64 thousand rows, 37.37 GB (3.93 thousand rows/s., 157.17 MB/s.)
image
  • After:
1 row in set. Elapsed: 199.619 sec. Processed 934.64 thousand rows, 37.37 GB (4.68 thousand rows/s., 187.22 MB/s.)
image

That's -22s from before, -16% overall.

@bobrik

bobrik commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

I backported #88213 and it helped to unlock quite a bit of a drop:

1 row in set. Elapsed: 102.095 sec. Processed 934.64 thousand rows, 37.37 GB (9.15 thousand rows/s., 366.05 MB/s.)
image

We're down to -57% now.

@bobrik

bobrik commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

Bad news: things break down with 64 threads. We are in fact slower with forced parallelism (15s vs 9s):

  • merge_tree_min_rows_for_concurrent_read = 1
  • merge_tree_min_bytes_for_concurrent_read = 0

Without it we're still faster (29s vs 32s).

Us running v24.8 doesn't help. I'll see what can be backported and then improved upon.

@bobrik

bobrik commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

With 50f21458f56e backported and updates from #114982, we're down to this with 64 threads:

  • Before:
1 row in set. Elapsed: 9.868 sec. Processed 934.64 thousand rows, 37.37 GB (94.72 thousand rows/s., 3.79 GB/s.)
Peak memory usage: 91.58 GiB.
  • After:
1 row in set. Elapsed: 4.513 sec. Processed 934.64 thousand rows, 37.37 GB (207.11 thousand rows/s., 8.28 GB/s.)
Peak memory usage: 39.71 GiB.
image

That's -54% runtime, -56% memory usage (-52GiB!). That's more like it.

For 1 thread, the time is still great:

1 row in set. Elapsed: 104.235 sec. Processed 934.64 thousand rows, 37.37 GB (8.97 thousand rows/s., 358.54 MB/s.)
Peak memory usage: 10.62 GiB.
image

@bobrik

bobrik commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

See also: #115925.

@bobrik

bobrik commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

I split off #115961 as a separate PR to keep things more bite sized for review/merge purposes.

@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from 913aa4f to f736e40 Compare August 23, 2026 00:33
This establishes the baseline performance of plan vs low-cardinality:

| Width           |     Plain | LC before | LC speedup over plain |
|-----------------|----------:|----------:|----------------------:|
| `UInt8`         |  0.0565 s |  0.1220 s |                 0.46x |
| `UInt16`        |  0.1019 s |  0.1703 s |                 0.60x |
| `UInt32`        |  0.1923 s |  0.1884 s |                 1.02x |
| `UInt64`        |  0.2476 s |  0.1952 s |                 1.27x |
| `UInt128`       |  0.5048 s |  0.5676 s |                 0.89x |
| `UInt256`       |  1.0715 s |  0.9354 s |                 1.15x |
| `String` (6 B)  |  0.5487 s |  0.2535 s |                 2.16x |
| `String` (26 B) |  0.6871 s |  0.2521 s |                 2.73x |
| `String` (56 B) |  0.8557 s |  0.2689 s |                 3.18x |
@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from f736e40 to d643c52 Compare August 26, 2026 22:42
@bobrik

bobrik commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

There were some fairly significant conflicts with #96630 and #115604. cc @thevar1able to see if I botched it.

I validated the improvement in the description and it still holds.

Previously dictionary position to aggregate state mappings were only valid
within a block. For parts where there's only a single dictionary, this is
too restrictive and resulted in repeated work.

This moves the mapping cache to the aggregation method, matching its lifetime
to the aggregation hash table. We keep the successful mappings while the dict
remains unchanged. Non-shared dictionaries remain block local.

This gives a very nice speedup to the benchmark in the previous commit:

| Width           | LC before |  LC after | Change |
|-----------------|----------:|----------:|-------:|
| `UInt8`         |  0.1220 s |  0.1158 s |  -5.1% |
| `UInt16`        |  0.1703 s |  0.1395 s | -18.1% |
| `UInt32`        |  0.1884 s |  0.1489 s | -20.9% |
| `UInt64`        |  0.1952 s |  0.1513 s | -22.5% |
| `UInt128`       |  0.5676 s |  0.5649 s |  -0.5% |
| `UInt256`       |  0.9354 s |  0.9206 s |  -1.6% |
| `String` (6 B)  |  0.2535 s |  0.1598 s | -37.0% |
| `String` (26 B) |  0.2521 s |  0.1630 s | -35.4% |
| `String` (56 B) |  0.2689 s |  0.1655 s | -38.5% |

The benefit is largest when many blocks share the same dictionary,
because dictionary-position mappings are reused across those blocks.
@bobrik
bobrik force-pushed the ivan/single-dict-aggregator branch from d643c52 to af50e9d Compare August 27, 2026 04:15
@bobrik

bobrik commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

See also: #115925.

@bobrik
bobrik marked this pull request as draft August 28, 2026 22:30
@bobrik

bobrik commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Marking as draft as #115925 appears to be a better approach.

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.

3 participants