Skip to content

Aggregate single-dictionary LowCardinality keys by index - #115925

Open
bobrik wants to merge 33 commits into
ClickHouse:masterfrom
bobrik:ivan/aggregate-by-index
Open

bobrik wants to merge 33 commits into
ClickHouse:masterfrom
bobrik:ivan/aggregate-by-index

Conversation

@bobrik

@bobrik bobrik commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

This is perhaps a simpler/better alternative to #114993. I'm reusing the first benchmark commit from there. Notice that it does not depend on #114982 to speed up aggregations of wide integers.

When a MergeTree part has one verified LowCardinality dictionary, its indexes uniquely identify values throughout the part. Use these indexes directly as aggregation keys and retain the dictionary for result finalization.

Merge parallel aggregation states directly when they share the same dictionary. Normalize back to value-based aggregation when the dictionary changes.

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

Width LC before LC after Change
UInt8 0.1209 s 0.1212 s +0.3%
UInt16 0.1697 s 0.1710 s +0.7%
UInt32 0.1896 s 0.1475 s -22.2%
UInt64 0.1977 s 0.1459 s -26.2%
UInt128 0.5752 s 0.1520 s -73.6%
UInt256 0.9080 s 0.1603 s -82.3%
String (6 B) 0.2532 s 0.1466 s -42.1%
String (26 B) 0.2489 s 0.1474 s -40.8%
String (56 B) 0.2609 s 0.1501 s -42.5%

Changelog category (leave one):

  • Performance Improvement

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

Speed up single dictionary LowCardinality aggregations by aggregating keys by dictionary index.


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

@bobrik
bobrik force-pushed the ivan/aggregate-by-index branch from 278e7a8 to ebefc4a Compare August 22, 2026 18:45
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [82164e0]

Summary: ❌

job_name test_name status info comment
Build (amd_msan) FAIL
Relocation headroom FAIL cidb
Stress test (arm_release) FAIL
Logical error: Load job 'A' waits for dependent load job 'B (STID: 1912-2f94) FAIL cidb
Performance Comparison (arm_release, master_head, 8/8) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_local, 2/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_local, 3/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_s3, 2/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_s3, 3/3) FAIL Performance dashboard
Check Results FAIL
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR aggregates verified single-dictionary LowCardinality keys by index, shares work across dictionary shards, and normalizes states for value-based merging and spilling. Reviewed head 82164e0705e3af83c7c3306c8a3cb8a93870fd48. One blocking regression remains: unused dictionary entries reach expressions after aggregation and can make a previously successful query throw.

Output consumers traced:

  • Native serialization compacts the selected range.
  • Both Arrow writers now compact referenced values.
  • Row formats resolve row indexes; ORC output materializes values.
  • Sorting, indexing, and filtering preserve dictionary mappings.
  • lowCardinalityKeys compacts; lowCardinalityIndices intentionally returns implementation indexes.
  • Aggregation output statistics count referenced dictionary payloads.
  • Generic IFunction dictionary evaluation processes unused entries, causing the finding below.
Findings

❌ Blockers

  • src/Interpreters/AggregationMethod.cpp:154 — Filtered-out keys affect post-aggregation expression evaluation. Consider one Wide part containing (id=1, k=3, v=1) and (id=2, k=1000001, v=2), where k is LowCardinality(UInt64) and the part uses one dictionary:

    SELECT space(k), sum(v)
    FROM t WHERE id = 1 GROUP BY k
    SETTINGS max_threads = 1, max_rows_to_group_by = 0,
             optimize_aggregation_in_order = 0, use_columns_cache = 0;

    Previously the aggregation output dictionary contained only default 0 and surviving key 3. The new output retains 1000001. space inherits canBeExecutedOnDefaultArguments = true, so replaceLowCardinalityColumnByNestedAndGetDictionaryIndexes passes the entire dictionary to its execution (src/Functions/IFunction.cpp:135–140,591–621). FunctionSpace::checkRepeatTime throws TOO_LARGE_STRING_SIZE for the discarded key. The valid query should return three spaces and 1. Enforce safe handling at the shared aggregation output or generic dictionary-evaluation boundary, covering expression consumers as well as format writers.

Tests
  • ⚠️ Add a focused stateless regression for an expression over an aggregated key whose retained dictionary contains an invalid, filtered-out value. The inline finding includes a complete fixture. Check both dictionary-index aggregation and a value-keyed control.
Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this job, so the new finding is established by tracing the current producer, expression adaptor, and space implementation. A focused regression run would provide runtime confirmation.
  • ⚠️ Current-head Fast test evidence shows 18 new stateless tests passing and eight skipped. Full stateless, unit, sanitizer, and performance jobs had not supplied results when inspected. Their completed reports are still needed for full validation; zero-result report headings are not successful test runs.
Final Verdict

Status: ❌ Block

Preserve expression semantics for shared aggregation dictionaries and add the focused regression before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 22, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
@bobrik
bobrik force-pushed the ivan/aggregate-by-index branch 2 times, most recently from a94b432 to ae41fea Compare August 23, 2026 00:08
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 82164e070 with master 9f7ed3169 (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 ⚠️

118 object files changed (+3.12 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 33.73 MiB 36.15 MiB +2.43 MiB (+7.19%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/Merge.cpp.o 12.95 MiB 13.25 MiB +308.28 KiB (+2.33%)
src/CMakeFiles/dbms.dir/Processors/Transforms/AggregatingTransform.cpp.o 690.10 KiB 830.76 KiB +140.66 KiB (+20.38%)
src/CMakeFiles/dbms.dir/Interpreters/AggregatorThresholdTopK.cpp.o 2.09 MiB 2.16 MiB +80.41 KiB (+3.77%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/Producer.cpp.o 2.68 MiB 2.73 MiB +49.13 KiB (+1.79%)
src/CMakeFiles/dbms.dir/Processors/Transforms/LimitByTransform.cpp.o 1.56 MiB 1.59 MiB +27.30 KiB (+1.71%)

716 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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds a specialized aggregation path that hashes LowCardinality dictionary indexes directly when a MergeTree part is verified to use a single dictionary, touching the aggregation hot path (ColumnsHashing, AggregationMethod, Aggregator). The only flagged query is ClickBench Q28, a LowCardinality GROUP BY that legitimately exercises this new code, so the flag is on-path and not downgraded. The +5.5% (median 1066ms to 1125ms) is marginal: the two tests disagree, CPU time is essentially flat (15571ms vs 15644ms), and the query has a noisy history, so this is inconclusive rather than a confirmed regression. Worth a re-run to confirm before drawing any conclusion.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1066 1125 +5.5% 0.0161 aggregation: Q28 is a GROUP BY on a LowCardinality column, exactly the path this PR's new single-dictionary-index aggregation method touches. The +5.5% is borderline (tests disagree) on an intrinsically noisy query, so treat it as 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: bfe888f0-240c-4241-aa9c-3171a5e57bd5
  • MIRAI run: 43f91362-29e6-4e54-ae22-ac3a443c25cd
  • PR check IDs:
    • clickbench_150867_1789392910
    • clickbench_150873_1789392910
    • clickbench_150879_1789392910
    • tpch_adapted_1_official_150890_1789392911
    • tpch_adapted_1_official_150901_1789392910
    • tpch_adapted_1_official_150939_1789392911

@bobrik
bobrik force-pushed the ivan/aggregate-by-index branch from ae41fea to 6840f0f Compare August 26, 2026 21:55
@bobrik

bobrik commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

Rebased to resolve the trivial include conflicts with #116267.

@bobrik

bobrik commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

While the conflicts were minimal, #96630 did change the code to cause compilation errors after the rebase.

I adjusted the code to work with the new topk optimization. cc @thevar1able

@bobrik
bobrik force-pushed the ivan/aggregate-by-index branch from 6840f0f to 57b4f16 Compare August 26, 2026 23:01
Comment thread src/Interpreters/Aggregator.cpp Resolved
Comment thread src/Interpreters/Aggregator.cpp Resolved
@bobrik
bobrik force-pushed the ivan/aggregate-by-index branch from bc96b1c to 9b21c3b Compare August 27, 2026 03:14
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
@bobrik
bobrik force-pushed the ivan/aggregate-by-index branch 2 times, most recently from c3c4cfb to bd53f1a Compare August 28, 2026 00:22
@bobrik

bobrik commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

I added specialization to squeeze a bit more out of it based on benchmarks on bigger data:

image

@bobrik

bobrik commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Table schema

CREATE TABLE profiles_v4_replica ...
CREATE TABLE profiles_v4_replica
(
    `timestamp` DateTime CODEC(DoubleDelta, ZSTD(1)),
    `duration` UInt32 CODEC(T64, ZSTD(1)),
    `profileType` LowCardinality(String) CODEC(ZSTD(1)),
    `serviceName` LowCardinality(String) CODEC(ZSTD(1)),
    `label_build_id` LowCardinality(String) CODEC(ZSTD(1)),
    `label_colo_allegiance` LowCardinality(String) CODEC(ZSTD(1)),
    `label_app_name` LowCardinality(String) CODEC(ZSTD(1)),
    `label_colo_name` LowCardinality(String) CODEC(ZSTD(1)),
    `label_colo_owner` LowCardinality(String) CODEC(ZSTD(1)),
    `label_colo_region` LowCardinality(String) CODEC(ZSTD(1)),
    `label_cpu_arch` LowCardinality(String) CODEC(ZSTD(1)),
    `label_debian_release` LowCardinality(String) CODEC(ZSTD(1)),
    `label_edge_reboot_release` LowCardinality(String) CODEC(ZSTD(1)),
    `label_environment` LowCardinality(String) CODEC(ZSTD(1)),
    `label_exe` LowCardinality(String) CODEC(ZSTD(1)),
    `label_hardware_generation` LowCardinality(String) CODEC(ZSTD(1)),
    `label_instance` LowCardinality(String) CODEC(ZSTD(1)),
    `label_kernel_release` LowCardinality(String) CODEC(ZSTD(1)),
    `label_kubernetes_cluster` LowCardinality(String) CODEC(ZSTD(1)),
    `label_kubernetes_container_name` LowCardinality(String) CODEC(ZSTD(1)),
    `label_kubernetes_namespace` LowCardinality(String) CODEC(ZSTD(1)),
    `label_kubernetes_pod_name` LowCardinality(String) CODEC(ZSTD(1)),
    `label_node_status` LowCardinality(String) CODEC(ZSTD(1)),
    `label_node_type` LowCardinality(String) CODEC(ZSTD(1)),
    `label_package_version` LowCardinality(String) CODEC(ZSTD(1)),
    `label_pop_name` LowCardinality(String) CODEC(ZSTD(1)),
    `label_sliver` LowCardinality(String) CODEC(ZSTD(1)),
    `label_tier` LowCardinality(String) CODEC(ZSTD(1)),
    `sumOfValues` UInt64 CODEC(T64, ZSTD(1)),
    `profile` String CODEC(ZSTD(3)),
    `stackMap.stack` Array(LowCardinality(UInt128)),
    `stackMap.value` Array(UInt64)
)
ENGINE = MergeTree
PARTITION BY toDate(timestamp)
ORDER BY (serviceName, profileType, label_app_name, label_instance, timestamp)
SETTINGS index_granularity = 8192

There are:

  • 190,244,623 plain rows
  • 15,144,156,707 rows after ARRAY JOIN stackMap.

These are the parts and their sizes (in MiB):

$ du -ms ~/clickhouse/data/default/profiles_v4_replica/*
35370   /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_1_1_0
34312   /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_2_2_0
123     /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_3_3_0
109     /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_4_4_0
37      /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_5_5_0
26      /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_6_6_0
14      /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_7_7_0
5       /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_8_8_0
1       /home/ivan/clickhouse/data/default/profiles_v4_replica/20260818_9_9_0
0       /home/ivan/clickhouse/data/default/profiles_v4_replica/detached
1       /home/ivan/clickhouse/data/default/profiles_v4_replica/format_version.txt

Queries

Aggregate by an Array(LowCardinality(UInt128)) column

1 thread

SELECT count()
FROM
(
    SELECT
        stackMap.stack AS stack,
        sum(stackMap.value) AS value
    FROM 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
  • Baseline:
ivan@36com1306:~/projects/clickhouse/build$ ../bench.py --clickhouse=/tmp/clickhouse-9d8eed34c114 --path=$HOME/clickhouse --runs=3 --query="SELECT count() FROM ( SELECT stackMap.stack AS stack, sum(stackMap.value) AS value FROM 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"
wall: 209.95s, cpu: 209.88s, memory:   4.57GiB
wall: 208.42s, cpu: 208.35s, memory:   4.57GiB
wall: 210.03s, cpu: 209.97s, memory:   4.57GiB
  • Patched:
ivan@36com1306:~/projects/clickhouse/build$ ../bench.py --clickhouse=/tmp/clickhouse-bd53f1a23f7d --path=$HOME/clickhouse --runs=3 --query="SELECT count() FROM ( SELECT stackMap.stack AS stack, sum(stackMap.value) AS value FROM 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"
wall: 151.70s, cpu: 151.64s, memory:   4.57GiB
wall: 150.55s, cpu: 150.50s, memory:   4.57GiB
wall: 150.60s, cpu: 150.54s, memory:   4.57GiB

The speedup here is not as good as I would like because one reader reads multiple parts, which means that is sees multiple dictionaries, which in turn means falling back to the previous aggregation path that is more expensive. Keeping the optimization going is probably feasible, but it would make this PR even bigger, so I'm not sure if it's a good idea (it's already quite big). It would be a nice win though. The current results show us doing the fast path only on the first part with about half of the data.

64 threads, default parallelism

SELECT count()
FROM
(
    SELECT
        stackMap.stack AS stack,
        sum(stackMap.value) AS value
    FROM 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 = 64
  • Baseline:
$ ../bench.py --clickhouse=/tmp/clickhouse-9d8eed34c114 --path=$HOME/clickhouse --runs=3 --query="SELECT count() FROM ( SELECT stackMap.stack AS stack, sum(stackMap.value) AS value FROM 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 = 64"
wall:  51.90s, cpu: 279.78s, memory:   9.27GiB
wall:  51.38s, cpu: 275.69s, memory:   9.76GiB
wall:  51.95s, cpu: 280.98s, memory:   9.28GiB
image
  • Patched:
ivan@36com1306:~/projects/clickhouse/build$ ../bench.py --clickhouse=/tmp/clickhouse-bd53f1a23f7d --path=$HOME/clickhouse --runs=3 --query="SELECT count() FROM ( SELECT stackMap.stack AS stack, sum(stackMap.value) AS value FROM 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 = 64"
wall:  20.03s, cpu:  97.93s, memory:   9.02GiB
wall:  20.41s, cpu:  99.08s, memory:   9.08GiB
wall:  21.08s, cpu: 100.96s, memory:   9.10GiB

-60% wall time, -64% CPU time! Same memory usage. Pretty good.

image

64 threads, more parallelism

SELECT count()
FROM
(
    SELECT
        stackMap.stack AS stack,
        sum(stackMap.value) AS value
    FROM 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 = 64, merge_tree_min_rows_for_concurrent_read = 1, merge_tree_min_bytes_for_concurrent_read = 0, merge_tree_min_read_task_size = 1, merge_tree_min_bytes_per_read_stream = 0
  • Baseline:
$ ../bench.py --clickhouse=/tmp/clickhouse-9d8eed34c114 --path=$HOME/clickhouse --runs=3 --query="SELECT count() FROM ( SELECT stackMap.stack AS stack, sum(stackMap.value) AS value FROM 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 = 64, merge_tree_min_rows_for_concurrent_read = 1, merge_tree_min_bytes_for_concurrent_read = 0, merge_tree_min_read_task_size = 1, merge_tree_min_bytes_per_read_stream = 0"
wall:   8.48s, cpu: 490.35s, memory:  39.96GiB
wall:   8.56s, cpu: 484.85s, memory:  40.79GiB
wall:   8.41s, cpu: 483.84s, memory:  40.40GiB
  • Patched:
ivan@36com1306:~/projects/clickhouse/build$ ../bench.py --clickhouse=/tmp/clickhouse-bd53f1a23f7d --path=$HOME/clickhouse --runs=3 --query="SELECT count() FROM ( SELECT stackMap.stack AS stack, sum(stackMap.value) AS value FROM 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 = 64, merge_tree_min_rows_for_concurrent_read = 1, merge_tree_min_bytes_for_concurrent_read = 0, merge_tree_min_read_task_size = 1, merge_tree_min_bytes_per_read_stream = 0"
wall:   8.61s, cpu: 488.46s, memory:  40.26GiB
wall:   8.40s, cpu: 486.40s, memory:  41.24GiB
wall:   8.62s, cpu: 496.56s, memory:  40.52GiB

It seems that task stealing disengages the optimization due to dictionary changes here too.

@bobrik

bobrik commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Single thread north star:

wall:  78.81s, cpu:  78.74s, memory:   4.53GiB
wall:  78.70s, cpu:  78.65s, memory:   4.53GiB
wall:  78.14s, cpu:  78.10s, memory:   4.53GiB

That's -62% from the baseline. I'm trying to figure out how to not mess up parallel queries while doing this.

@bobrik

bobrik commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

I added a commit to preserve indexing across dictionary switches without compromising CPU or memory costs.

  • Wall time:
Configuration Baseline Before Before vs baseline After After vs before After vs baseline
1 thread 210.0s 150.6s -28.3% 78.6s -47.8% -62.6%
64 threads 51.9s 20.4s -60.7% 17.4s -14.6% -66.4%
64 threads, smallest read tasks 8.5s 8.6s +1.5% 8.1s -5.7% -4.2%
  • CPU time:
Configuration Baseline Before Before vs baseline After After vs before After vs baseline
1 thread 209.9s 150.5s -28.3% 78.6s -47.8% -62.6%
64 threads 279.8s 99.1s -64.6% 100.3s +1.2% -64.2%
64 threads, smallest read tasks 484.9s 488.5s +0.7% 358.0s -26.7% -26.2%
  • Peak memory:
Configuration Baseline Before Before vs baseline After After vs before After vs baseline
1 thread 4.57 GiB 4.57 GiB 0.0% 4.53 GiB -0.9% -0.9%
64 threads 9.28 GiB 9.08 GiB -2.2% 8.97 GiB -1.2% -3.3%
64 threads, smallest read tasks 40.4 GiB 40.5 GiB +0.3% 35.3 GiB -12.8% -12.6%

No impact to numbers in the description as those exercise one part to begin with.

@bobrik
bobrik force-pushed the ivan/aggregate-by-index branch 2 times, most recently from c1418c4 to 2fc1f49 Compare August 28, 2026 22:00
alexey-milovidov and others added 3 commits November 9, 2026 20:17
…s after an ineligible block

An eligible dictionary A, then an ineligible block (e.g. from a `Compact` part), then
dictionary C enabled dictionary shards through the ineligible-block branch of
`AggregatingTransform::consume`, bypassing the `spilling_under_memory_pressure` check
applied on a dictionary switch. Apply the same restriction there.

Extend `05565_low_cardinality_dictionary_spill_scheduler` with the A -> `Compact` -> C
sequence under `enable_adaptive_memory_spill_scheduler = 1` with both external
aggregation thresholds zero, and pin `use_columns_cache = 0` and
`enable_parallel_replicas = 0` in its aggregation queries.

ClickHouse#115925

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Columns served from the columns cache do not carry the shared dictionary of the
part, so with randomized `use_columns_cache = 1` the queries never reach the
dictionary index path these tests exercise. `05093_low_cardinality_dictionary_memory_backpressure`
then timed out waiting for the owner pause failpoint (TSan and MSan flaky checks),
and `05060_low_cardinality_dictionary_eligibility_transitions` lost its index
aggregation lines. The same fix was applied to `05087` earlier. Also pin
`enable_parallel_replicas = 0` in `05060`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115925&sha=60033cee76c2c72bc4670bb1b2c7e12468e233b8
ClickHouse#115925

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master now counts the rows of each dictionary position of a block for
`GROUP BY lc_key` with `count()` alone, and does one lookup per distinct position.
That beats the index-keyed table: the performance test
`group_by_multi_low_cardinality` query 2 (`SELECT metric, count() ... GROUP BY metric`)
was 48% slower with this PR (confirmed on rerun). `canUseSingleLowCardinalityDictionary`
now returns false when `is_simple_count`; `can_reorder_dictionary_aggregation`
is computed after the top-K adjustment of `is_simple_count`.

`05045` gets a second aggregate to keep exercising the index path, and the
`inline_count` case of `05080` now expects no dictionary switches.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115925&sha=60033cee76c2c72bc4670bb1b2c7e12468e233b8
ClickHouse#115925

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed three fixes:

  • 1682955: addresses the review. Spill-scheduled queries no longer enter dictionary shards after an ineligible block. Regression case added to 05565.
  • d09d609: fixes the failures of 05093 (TSan/MSan flaky checks) and 05060 (ParallelReplicas). Both runs had randomized use_columns_cache = 1. Columns served from that cache lose the part's shared dictionary, so the query never reached the dictionary path. 05093 then waited for the failpoint until it timed out. I pinned use_columns_cache = 0 in all the dictionary aggregation tests, as 05087 already did. 30 randomized runs pass locally.
  • a789397: fixes the confirmed performance regression in group_by_multi_low_cardinality query 2 (SELECT metric, count() ... GROUP BY metric, +48%). Master now has an inline per-dictionary-position count (fbedcd85d866), and it is faster than the index-keyed table. The index path is now skipped when count() is the only aggregate (is_simple_count). The PR's own benchmark uses sum and is not affected.

Still open, needs a human decision: MSan Relocation headroom. The binary's code grew by about 5 MiB, slightly over the 5 MiB step threshold; 464 MiB of headroom remains. If that growth is acceptable, it needs the ci-relocation-headroom-ok label. The iceberg performance shards (Insert historical data) and Build profile diff (LogClusterNotReady) failed on CI infrastructure, unrelated to this PR.

Comment thread src/Interpreters/AggregationMethod.cpp Resolved
alexey-milovidov and others added 3 commits November 11, 2026 01:38
…statistics

Aggregation by dictionary index emits key columns that share the source
dictionary, and `ColumnLowCardinality::byteSize` does not count a shared
dictionary. `RuntimeDataflowStatisticsCacheUpdater::recordAggregationKeySizes`
and `MaterializedKeyBytesMeter` priced the keys by `byteSize`, so the output
bytes of the automatic parallel replicas cost model dropped to the indexes
alone (about 4 KB instead of about 540 KB for 1000 keys of 1 KiB).

Count the referenced dictionary values explicitly in both paths, and add a
regression test that compares an eligible single-part aggregation with a
value-keyed control.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A query whose only aggregate is `count` takes the inline-count path and
bypasses aggregation by dictionary index, so the typed cases of the test no
longer covered it. `sum(1)` does not help: the analyzer rewrites it to
`count`. Add a checked `uniqExact(id)` to each subquery, and assert via
`AggregationSingleLowCardinalityDictionarySwitches` that the two-part typed
queries take the dictionary-index path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/115925/a78939781a0ef2f49707457c03a9ce8051151aac/pr/stress_test_amd_tsan/hung_check.log (Stress test (amd_tsan) hung check: SELECT anyDistinct(repeat('x', 100)) OVER (ROWS BETWEEN 10 PRECEDING AND UNBOUNDED FOLLOWING) FROM numbers(5000000), a window function query that does not touch the LowCardinality dictionary aggregation of this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Other failures at a789397:

  • Performance Comparison (amd_release, master_head, 2/6) enum #4 is a plain Enum8 cast with no GROUP BY, so this PR's code isn't on its path.
  • The iceberg_local / iceberg_s3 performance jobs failed on a missing all-query-metrics.tsv (CI infrastructure).
  • Build (amd_msan) Relocation headroom is caused by this PR: unit_tests_dbms grows by 5.67 MiB (limit 5 MiB) from the new templated aggregation code. A maintainer needs to decide whether that is acceptable (ci-relocation-headroom-ok label) or the code should be slimmed down.

This push merges master and addresses both review threads (shared-dictionary bytes in the output statistics, and keeping the 05024 typed cases on the dictionary-index path).

@groeneai

Copy link
Copy Markdown
Collaborator

This hang is not caused by this PR. The query is stuck in AggregateState::add under AggregateWindowFunctionRecalculate::evaluate (a moving-frame-start window aggregate), which lost its cancellation check in #129257 (here it ran 731 s with max_execution_time = 10). It is already fixed by #130328 (merged 2026-11-10), which adds a periodic checkTimeLimit call (honouring both max_execution_time and KILL QUERY) in AggregateState::add, the exact frame in this hung_check.log.

The failing run at a789397, including the merge with master that CI built, does not contain the fix (286 commits behind its merge commit ebf03a4), while the new head 31a6b14 does, so no separate PR is needed.

alexey-milovidov and others added 2 commits November 12, 2026 07:15
# Conflicts:
#	src/Interpreters/Aggregator.cpp
`05024`: the CI profile (`tests/config/users.d/limits.yaml`) sets
`max_rows_to_group_by`, which disables aggregation by dictionary index, so
the two-part typed queries never switched dictionaries and the
`AggregationSingleLowCardinalityDictionarySwitches` checks returned 0. Pin
`max_rows_to_group_by = 0` (and `use_columns_cache = 0`, as in the other
dictionary aggregation tests).

`05620`: `SHA256` is not available in the Fast test build. Use `sipHash128`
to generate the poorly compressible keys, and check only the ratio of the
output bytes instead of their exact build-dependent values.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115925&sha=31a6b14761d99ff13b566bb786f9415b14f049fd&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (one trivial include conflict in Aggregator.cpp) and fixed the two Fast test failures in 774ca8e:

  • 05024: the CI profile (tests/config/users.d/limits.yaml) sets max_rows_to_group_by: 10G. getSingleLowCardinalityDictionaryForBlock turns off aggregation by dictionary index under any max_rows_to_group_by limit, so the two-part typed queries normalized to value-based aggregation and recorded no dictionary switches. The test now pins max_rows_to_group_by = 0 and use_columns_cache = 0, as the other dictionary aggregation tests already do.
  • 05620: the Fast test build has no SHA256. The keys are now generated with sipHash128, and the test checks only the ratio of the output bytes instead of exact values that depend on the build.

All 25 tests of this PR pass locally against a server that uses the CI limits.yaml profile.

@groeneai, thanks for tracing the Stress test (amd_tsan) hang to #130328. That fix is now in this branch.

Still needs a human decision: the MSan Relocation headroom growth (about 5.7 MiB against the 5 MiB step), i.e. whether to apply ci-relocation-headroom-ok or slim down the templated code.

…ndex

Resolve conflicts with the adaptive aggregation merge rework on master:
- `mergeSingleLevelPartitionsAndConvertToChunk` takes `destination_size_hint`; keep the dictionary copy for the destination.
- `prepareVariantsToMerge` accepts indexed single-level sources of the bucket-merge destination.
- `prepareAdaptiveTopKPruning` was renamed to `prepareAdaptiveTopK`.
- Dictionary indexes are normalized whenever the adaptive merge goes by buckets (`mergesByBuckets`), not only when engaged, since the destination is value-keyed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (026654f02583). Conflicts were with the adaptive aggregation merge rework on master:

  • mergeSingleLevelPartitionsAndConvertToChunk now takes destination_size_hint; the dictionary copy into the destination is kept.
  • prepareVariantsToMerge keeps this PR's arena deduplication and also accepts master's indexed single-level sources of the bucket-merge destination.
  • prepareAdaptiveTopKPruning was renamed to prepareAdaptiveTopK in the gtests.
  • Semantic fix: dictionary indexes are now normalized whenever the adaptive merge goes by buckets (mergesByBuckets, which on master is also true for top-K pruning without a frozen producer), not only when the session is engaged. The bucket-merge destination is value-keyed.

Every changed TU compiles. I could not link the binary locally because of memory limits on the shared machine, so CI has to confirm the link.

Comment thread src/Interpreters/AggregationMethod.cpp Resolved
alexey-milovidov and others added 2 commits November 18, 2026 05:54
# Conflicts:
#	src/Interpreters/Aggregator.cpp
#	src/Interpreters/Aggregator.h
…lues in Arrow

Both Arrow writers (`ArrowIPCBlockOutputFormat::encodeDictionaryColumn` and
`fillArrowArrayWithLowCardinalityColumnDataImpl`) serialized the whole dictionary of a
`LowCardinality` column. A `MergeTree` part dictionary that the reader shares with the
column, or a dictionary that `filter` left unchanged, holds values of rows that were
filtered out, e.g. by a row policy, so they were disclosed in the output. This already
happened for a plain `SELECT` and the aggregation by dictionary index extends it to
`GROUP BY` results. Compact the dictionary to the values that the rows reference
(`cutAndCompact`) before encoding it.

Add a test with a restricted user over HTTP.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115925&sha=026654f0258385a6dff41787a0fd63e4f4d58850&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29 (limit_by_in_pk_order query 10, a LIMIT BY without aggregation or LowCardinality; it also failed on master on 2026-11-15 and in #131355) and the Performance Comparison (arm_release, master_head, iceberg_local/iceberg_s3) jobs, which fail with all-query-metrics.tsv was not found (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115925&sha=026654f0258385a6dff41787a0fd63e4f4d58850&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%20iceberg_local%2C%201%2F3%29), and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Performance Comparison (arm_release, master_head, iceberg_*): this is the harness error fixed by #129874 (merged 2026-11-16). The run on 026654f predates that fix; the current head ff325de includes it through the master merge 7bc0510, so the next perf run of this PR no longer hits all-query-metrics.tsv was not found.

limit_by_in_pk_order #10: no fix is in progress yet, and #132328 does not cover it. #132328 changes the hash LimitByTransform (query #1 on arm_release from #131355), while query #10 (100 partitions read in order with allow_limit_by_partitions_independently = 1) runs LimitBySortedStreamTransform. What I measured so far:

  • In 30 days of CIDB this run is the only timing failure of query some doc typo fixes #10 (0.636 -> 0.778 s, +24.6% after the server restart). The master red of 2026-11-15 is the amd_llvm_coverage_per_test, per_query_coverage job, where 56 of 58 tests fail in shard 7/16, so it is not a timing result.
  • Both servers read the same data (1.2 GB decompressed, 18,600 blocks); the difference is user CPU, 4.56 -> 5.81 s.
  • This PR's diff does not touch MergeTree reading, the in-order merge or LimitBySortedStreamTransform.

That looks like a property of this binary rather than of the code on that path, but I have not proven it. I'm comparing that path's machine code in the two CI binaries and will follow up here with a PR or my findings.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 18, 2026 07:44

AI review of a later commit does not approve the PR, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on limit_by_in_pk_order #10 (amd_release 3/6): the slowdown comes from where this PR's binary places unchanged code. I have no code or test fix to propose for it.

  • The extra time is in one loop. LimitBySortedStreamTransform::transform and its two callees, ColumnVector<Int32>::getEqualRangeEndAssumeSorted and findFirstNotEqualImpl_x86_64_v4<int>, go from 198 to 921 CPU samples in the job's profile; all other frames together go down by 39. Their machine code is the same in the PR binary and in the reference dcf6e7b (address-normalized disassembly; transform differs only in one ProfileEvents index outside the per-run loop). Only their addresses differ.
  • Hardware counters of the job's prewarm run: both servers execute the same 55.6G instructions and 9.9G branches, but the PR server has 85M branch misses instead of 35M (about one more per run of two equal keys) and 20.2G cycles instead of 16.1G. All 7 runs and the 6 confirmation runs after the two server restarts were slow (medians about 0.78 s vs 0.63 s), so it is a property of this binary.
  • It is rare. Over 45 days, the query's user CPU differed by 9% or more in 4 of 3,647 amd runs. In only 2 of them was one side slower in every run: this one (+27%) and one other PR build (+17%); in the other 2, both sides vary from run to run. This PR's three earlier builds ran it at 0.99-1.01.
  • Changing this loop would only give it a new placement. My earlier change to a LIMIT BY loop for the same kind of red (Remove the leftover test-only failpoints and logging from the LIMIT BY loops #127172) put that loop into a 2x slower placement on arm, and I withdrew it.

The current head ff325de is a new build, so its perf run gets a new placement. If this class should stop blocking PRs, the fix is in the perf gate: do not block on a confirmed slowdown when the functions the query spends its time in have the same machine code in both binaries (option (a) in #131211 (comment)).

alexey-milovidov and others added 3 commits November 21, 2026 08:18
…ndex

Conflicts:
- `ColumnLowCardinality.cpp`: keep `tryAdoptSharedDictionary` (it covers the adoption of a shared dictionary by an empty column added on master) and read the current dictionary through the const overload, as on master.
- `ColumnLowCardinality.h`: take the `const_cast` + `getPtr` form of `create` from master and pass `has_single_dictionary_for_part`.
- `Aggregator.cpp`: use `AggregatedDataVariants::SizeHint` in `mergeSingleLevelPartitionsAndConvertToChunk` and the `state_cache` argument of `mergeStreamsImpl` in the dictionary index dispatch.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
- `AggregatedDataVariants::init` now takes a `SizeHint` instead of a number of keys; pass it for the normalized variant.
- `master` added `chassert(use_count() == 1)` to `assumeMutableRef`, which the non-const accessors of the `LowCardinality` dictionary go through. `ColumnLowCardinality::insertDictionaryIndex` and `AggregationMethodSingleLowCardinalityDictionaryIndex::insertKeyIntoColumns` only read a dictionary that is shared by design, so they now use the const overloads.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
- `modernize-use-nodiscard` for `getIndexAt`, `getHashAtIndex`, `hasOnlyOneValueSinceLastReset` and `getCacheMissesSinceLastReset` of `HashMethodSingleLowCardinalityDictionaryIndex`.
- `clang-analyzer-deadcode.DeadStores` for the unused second half of the structured binding of `std::ranges::unique` in `RuntimeDataflowStatistics.cpp`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115925&sha=ff325ded3669c3bac28d492ff7043966b0ef1cb0&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29
ClickHouse#115925

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (3312a1e93766) and fixed the red Build (arm_tidy) jobs.

Conflicts and the reconciliation with master (a2358f7b27f3):

  • ColumnLowCardinality.cpp: tryAdoptSharedDictionary is kept; it covers the adoption of a shared dictionary by an empty column that master added to doInsertRangeFrom. ColumnLowCardinality.h: create takes the const_cast + getPtr form from master and passes has_single_dictionary_for_part.
  • Aggregator.cpp: AggregatedDataVariants::init now takes a SizeHint, and the dictionary index dispatch in mergeStreamsImpl uses the new state_cache argument.
  • Master added chassert(use_count() == 1) to assumeMutableRef, which the non-const accessors of the LowCardinality dictionary go through. tryAdoptSharedDictionary, insertDictionaryIndex and AggregationMethodSingleLowCardinalityDictionaryIndex::insertKeyIntoColumns only read a dictionary that is shared by design, so they now use the const overloads. I found these by reading the code; I have no local debug build, so the debug and sanitizer jobs in CI have to confirm that no other such place is left.

clang-tidy (9aaaa6b8c474): [[nodiscard]] on four const methods of HashMethodSingleLowCardinalityDictionaryIndex, and the dead store of the structured binding in RuntimeDataflowStatistics.cpp. These were all the distinct errors in the four arm_tidy logs; I did not run clang-tidy locally.

All 26 stateless tests of this PR pass locally on the merged release build with the CI limits.yaml profile. The gtests compile; I did not run them.

@groeneai, thanks for the analysis of limit_by_in_pk_order #10 (a code placement effect of that binary, with identical machine code on the hot path) and of the iceberg performance jobs (#129874). Nothing to change in this PR for either; the new build gets a new placement.

Still needs a human decision: the MSan Relocation headroom growth (ci-relocation-headroom-ok or slimming down the templated code).


auto & column = assert_cast<ColumnLowCardinality &>(*key_columns_low_cardinality[0]);
if (column.empty())
column.setSharedDictionary(dictionary);

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.

[Blocker] Keep unused dictionary values out of post-aggregation expression evaluation

Attaching the entire part dictionary here changes which values downstream expressions evaluate. For example, create one Wide part with a numeric LowCardinality key:

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (id UInt64, k LowCardinality(UInt64), v UInt64)
ENGINE = MergeTree ORDER BY id
SETTINGS min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0;
INSERT INTO t SETTINGS low_cardinality_use_single_dictionary_for_part = 1
VALUES (1, 3, 1), (2, 1000001, 2);

SELECT space(k), sum(v)
FROM t WHERE id = 1 GROUP BY k
SETTINGS max_threads = 1, max_rows_to_group_by = 0,
         optimize_aggregation_in_order = 0, use_columns_cache = 0;

The old aggregation builds an output dictionary containing only default 0 and surviving key 3. This path retains 1000001 too. space inherits canBeExecutedOnDefaultArguments = true, so IExecutableFunction::executeWithoutSparseColumns and replaceLowCardinalityColumnByNestedAndGetDictionaryIndexes evaluate the entire dictionary (src/Functions/IFunction.cpp:135-140,591-621). FunctionSpace::checkRepeatTime then throws TOO_LARGE_STRING_SIZE for the filtered-out key, although the only result should be three spaces and 1.

Please make the shared aggregation output safe for expression consumers, or restrict generic dictionary evaluation to referenced entries, and add a focused stateless regression. The Arrow-writer fixes do not cover this consumer.

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 manual approve Manual approve required to run CI pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants