Skip to content

Faster GROUP BY of fixed-width keys and one String - #129180

Merged
nihalzp merged 49 commits into
ClickHouse:masterfrom
nihalzp:fixed-width-keys-plus-string
Nov 18, 2026
Merged

nihalzp merged 49 commits into
ClickHouse:masterfrom
nihalzp:fixed-width-keys-plus-string

Conversation

@nihalzp

@nihalzp nihalzp commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Related: #110573
Related: #112089

Background

GROUP BY of fixed-width keys and one String key is common: an ID or a date with a name, a phrase or a URL. ClickBench Q16 is one:

SELECT UserID, SearchPhrase, count() FROM hits GROUP BY UserID, SearchPhrase ORDER BY count() DESC LIMIT 10

Master aggregates such keys with prealloc_serialized. It serializes the key columns of every row into one byte string, the bytes of UserID followed by the length and the bytes of SearchPhrase, and hashes that string. The hash table stores a reference to the bytes of each key, copied into an arena, and compares keys byte by byte. Every row pays for serializing and hashing its whole key, and every key is a reference to bytes elsewhere in memory, even when its string is empty.

A lone String key has a better method since #110573: key_packed_string keeps the string as a 16-byte packed reference, with short strings inline and the hash computed once. The new methods extend it to fixed-width keys and one String.

The key

keys32_packed_string, keys64_packed_string and keys128_packed_string apply when the keys are one non-nullable String and fixed-width values of 1, 2, 4, 8 or 16 bytes, at most 16 bytes in total. The key has two parts:

  • The fixed-width values, packed into one UInt32, UInt64 or UInt128 as the keys32, keys64 and keys128 methods pack them.
  • The string as a packed reference. It is 16 bytes and keeps strings of up to 11 bytes inline. When the fixed-width values fit in a UInt32, a 16-byte reference after them would leave 4 bytes of padding, so the key takes UnhashedPackedStringRef there: a 16-byte reference with 4-byte alignment and no hash, which keeps strings of up to 15 bytes inline, while the key keeps its hash in the 4 bytes that would be padding. Both keys take 24 bytes.

Keys with an empty string

An empty string is the usual form of a missing value. In hits, 86.8% of the rows have an empty SearchPhrase, and Q16 has 13.4 million groups with an empty phrase next to 10.7 million with another.

Like StringHashTable, the hash table of the new methods (KeysAndPackedStringHashMap) splits the keys by their string:

  • A key with an empty string goes into a table of its fixed-width values alone, hashed as in keys32, keys64 and keys128. Its cells are as narrow as theirs, 16 bytes for UserID against 32 for a key with a string.
  • The other keys go into a table of the whole key.

The adaptive aggregator stages the keys that miss a frozen table in the same spirit: a key with an empty string takes a record as narrow as that of a fixed-width key, without the string and its hash.

Without the adaptive aggregator, a repeated query preallocates its hash tables by the statistics of its earlier runs (collect_hash_table_stats_during_aggregation). One number of keys cannot size both tables of the new methods, so the statistics also record how many keys had an empty string, and the preallocation splits by that share.

Results

ClickBench hits (100M rows) on AWS c8a.16xlarge (64 cores, one thread per core), clickhouse-local, FORMAT Null. The baseline is the same build with enable_fixed_and_packed_string_keys_in_aggregation = 0, which aggregates these keys with prealloc_serialized, as master does. Peak memory is the peak of the query from --memory-usage.

QueryShape16 threads64 threads
TimePeak memoryTimePeak memory
Q11GROUP BY MobilePhone, MobilePhoneModel: count(DISTINCT UserID), where MobilePhoneModel <> ''38.8 → 39.0 ms, 0.99×101 → 97 MiB, −4%27.0 → 27.2 ms, 0.99×87 → 87 MiB, 0%
Q14GROUP BY SearchEngineID, SearchPhrase: count, where SearchPhrase <> ''95.8 → 89.9 ms, 1.07×1,211 → 1,133 MiB, −6%56.8 → 56.6 ms, 1.00×1,802 → 1,473 MiB, −18%
Q16GROUP BY UserID, SearchPhrase: count159.7 → 111.3 ms, 1.43×2,053 → 1,408 MiB, −31%84.1 → 62.6 ms, 1.34×2,619 → 2,068 MiB, −21%
Q18GROUP BY UserID, minute(EventTime), SearchPhrase: count227.1 → 169.5 ms, 1.34×3,204 → 2,367 MiB, −26%117.6 → 95.9 ms, 1.23×4,282 → 4,043 MiB, −6%
Geomean1.19×−18%1.13×−12%

Q11 and Q14 run keys32_packed_string, Q16 keys64_packed_string and Q18 keys128_packed_string. Q11 has 302 groups and spends its time in the states of count(DISTINCT UserID), and Q14 has no empty phrases, so they gain little.

ClickBench has no GROUP BY of a narrow key and a short string, whose strings keys32_packed_string keeps inline. A UInt32 and a String of 12 to 15 bytes, 20M rows, with 200 thousand groups in k, s and 2 million in k2, s2:

CREATE TABLE narrow_key_short_string (k UInt32, s String, k2 UInt32, s2 String) ENGINE = Memory;
INSERT INTO narrow_key_short_string
SELECT g % 1000, leftPad(toString(g), 12 + g % 4, '0'), g2 % 1000, leftPad(toString(g2), 12 + g2 % 4, '0')
FROM (SELECT cityHash64(number) % 200000 AS g, cityHash64(number, 1) % 2000000 AS g2 FROM numbers_mt(20000000));
Shape16 threads64 threads
TimePeak memoryTimePeak memory
GROUP BY k, s: count61.6 → 27.1 ms, 2.27×450 → 273 MiB, −39%47.2 → 39.4 ms, 1.20×1,715 → 1,207 MiB, −30%
GROUP BY k2, s2: count52.5 → 39.6 ms, 1.33×1,163 → 1,060 MiB, −9%48.6 → 38.9 ms, 1.25×1,945 → 1,061 MiB, −45%
GROUP BY k2, s2: count, enable_adaptive_aggregator = 0115.1 → 63.6 ms, 1.81×1,602 → 1,091 MiB, −32%62.7 → 45.2 ms, 1.39×2,804 → 2,117 MiB, −25%
Geomean1.76×−28%1.28×−34%
image

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY of fixed-width keys and one String key, such as GROUP BY UserID, minute(EventTime), SearchPhrase, uses a new hash table. It keeps strings of up to 11 bytes inside the key, or of up to 15 bytes when the fixed-width keys fit in 4 bytes, computes the hash of a key once, and stores keys with an empty string as narrow fixed-width keys. On four ClickBench queries that group by such keys, the geometric mean speedup is 1.19x at 16 threads and 1.13x at 64 threads, up to 1.43x, and peak memory drops by 18% and 12%. The new setting enable_fixed_and_packed_string_keys_in_aggregation is enabled by default; disabling it restores the previous hash table.


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dcde2f6]

Summary: ✅


AI Review

Summary

Reviewed #129180 at dcde2f6bec8931494e2571f0f67c4d2a729a6602. The PR adds packed aggregation keys for fixed-width values and one String, including empty-string specialization, adaptive staging, and distributed compatibility handling. No new inline findings were identified. One previously reported decoder safety concern remains below, marked as dismissed by the author; its thread remains resolved.

Findings

❌ Blockers

  • src/Interpreters/AdaptiveAggregation/StagedRecords.h:493 [dismissed by author -- https://github.com/Faster GROUP BY of fixed-width keys and one String #129180#discussion_r4601073980]: A malformed staged record must produce an exception before its declared lengths drive memory accesses. StagedKeysAndPackedStringKey::read accepts embedded lengths without an end boundary; walkStagedRecords advances its prefetch cursor by the resulting unchecked record size. A decoded record declaring a string larger than its remaining payload can therefore make the next prefetch decode outside the buffer, or make key persistence copy beyond it. The author's checksum explanation covers accidental compressed-block corruption, and no query or writer-call sequence producing inconsistent records was found. The remaining concern specifically requires checksum-valid malformed spill bytes: a checksum does not establish record boundaries. Validate the complete record within the available spill range before prefetching, reconstructing keys, or reading arguments.
Missing context / blind spots
  • ⚠️ No local build or executable was available, so validation was static. The fetched Praktika reports reported 15,029 passed checks/tests, zero failures, and 4,424 skipped tests; most reported test results came from the fast-test job.
Tests
  • ⚠️ Add a focused staged-record decoder test for a truncated header and a string or argument length exceeding the remaining decoded block. Exercise prefetching and key persistence, and require an exception before any out-of-bounds access. Existing valid-record spill tests do not establish this behavior.
Final Verdict

Status: ❌ Block. Minimum required action: bound and validate staged-record decoding at the spill-consumption boundary, with focused malformed-record coverage. This preserves the previously dismissed concern in the summary only; no new inline review or thread reopening is required.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 4, 2026
Comment thread src/Core/ProtocolDefines.h Resolved
@mintlify

mintlify Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit dcde2f6.

Approve preview

@nihalzp nihalzp added the ci-relocation-headroom-ok Accept an expected decrease of the relocation headroom in the build check label Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dcde2f6be with master 3634df08e (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 831.34 MiB 831.35 MiB +15.25 KiB (+0.00%)

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.

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

74 object files changed (+7.34 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 29.41 MiB 33.63 MiB +4.22 MiB (+14.36%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/Merge.cpp.o 10.51 MiB 12.46 MiB +1.94 MiB (+18.48%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/Producer.cpp.o 2.09 MiB 2.50 MiB +413.10 KiB (+19.28%)
src/CMakeFiles/dbms.dir/Interpreters/AggregatorThresholdTopK.cpp.o 1.45 MiB 1.69 MiB +246.56 KiB (+16.57%)
src/CMakeFiles/dbms.dir/Interpreters/AggregatedDataVariants.cpp.o 824.33 KiB 980.44 KiB +156.11 KiB (+18.94%)
src/CMakeFiles/dbms.dir/Processors/Transforms/LimitByTransform.cpp.o 1.45 MiB 1.58 MiB +131.56 KiB (+8.84%)
src/CMakeFiles/dbms.dir/Processors/Transforms/NegativeLimitByTransform.cpp.o 1.10 MiB 1.21 MiB +108.79 KiB (+9.65%)
src/CMakeFiles/dbms.dir/Interpreters/AggregationMethod.cpp.o 539.41 KiB 628.41 KiB +89.00 KiB (+16.50%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/AdaptiveAggregation.cpp.o 288.30 KiB 318.18 KiB +29.88 KiB (+10.36%)

711 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

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

Job report

Comment thread src/Interpreters/Aggregator.cpp Resolved
# Conflicts:
#	docs/resources/develop-contribute/native-protocol/protocol.mdx
#	src/Client/HedgedConnections.cpp
#	src/Client/MultiplexedConnections.cpp
#	src/Common/tests/gtest_packed_string_ref.cpp
…plus-string

# Conflicts:
#	src/Core/ProtocolDefines.h

@harikrishnan94 harikrishnan94 left a comment

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.

LGTM

…plus-string

# Conflicts:
#	src/Interpreters/AdaptiveAggregation/Merge.cpp
#	src/Interpreters/Aggregator.cpp
#	src/Planner/Planner.cpp
#	src/Processors/QueryPlan/QueryPlanSerializationSettings.cpp
…plus-string

# Conflicts:
#	src/Core/ProtocolDefines.h
#	src/Interpreters/tests/gtest_aggregator_adaptive_merge.cpp
…ngle-level merge, so `merge_cell` keeps master's call sites
Comment thread src/Processors/QueryPlan/RollupStep.cpp Resolved
…p` and `Cube` plan steps when it is off or cannot apply
@nihalzp

nihalzp commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

@groeneai Open an issue for this pre-existing leak, with a reproducer, and say in it whether it reproduces on master and which releases contain it. Aggregator::mergeDataOnlyExistingKeysImpl returns from its !found branch without destroying the source state, and clearAndShrink then drops the pointer, so the states of the groups that the merge discards leak when they own heap memory, as uniqExact does. It runs when group_by_overflow_mode = 'any' stops adding keys during the serial merge of single-level tables, with or without WITH TOTALS, because ConvertingAggregatedToChunksTransform emits the overflow row before it merges the tables: disable the adaptive aggregator and the parallel single-level merge, set both two-level thresholds to 0, and give the threads keys of their own. With uniqExact(number), the resident memory after SYSTEM JEMALLOC PURGE grew by about 227 MiB per run on my machine. Then link the issue here.

@groeneai

Copy link
Copy Markdown
Collaborator

Opened #132439 for the leak. It reproduces on master and on the latest release of every supported branch (26.10.5.57, 26.9.31.21, 26.8.39.19, 26.3.66.4), and on every older release I tested back to 23.8: about 260 MiB per query on 26.6 and later, about 560 MiB on 26.3 and older. Only max_rows_to_group_by with any and the two two-level thresholds are needed; enable_adaptive_aggregator and enable_parallel_single_level_merge do not change it, because planPartitionMerge already declines under that limit.

@nihalzp
nihalzp added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 5703367 Nov 18, 2026
380 of 381 checks passed
@nihalzp
nihalzp deleted the fixed-width-keys-plus-string branch November 18, 2026 09:07
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
…String keys

The merge of master brought ClickHouse#129180's shortcut into the frozen loop of argument records: a key of fixed-width values
and an empty String that repeats the last missed key is staged with that key's hash, without being hashed or probed.
The shortcut staged the row before the repeat check, so with the `keysN_packed_string` methods the repeats of such a
key were staged even when every aggregate ignores repeated values.

The repeat check is now a lambda that both paths call. A row on the shortcut takes the last missed key's hash, so the
check compares it with the previous row exactly as on the probed path.

The test gains a `GROUP BY k, e` case whose String key is empty in the first half of each key: results equal
`enable_adaptive_aggregator = 0`, and it stages less than half the records of a `sum` query. Measured on the debug
build: 40768 staged records with the change, 120736 without it, 200704 for `sum`; the binary without the change fails
only that check (`1 0`).

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

Labels

ci-relocation-headroom-ok Accept an expected decrease of the relocation headroom in the build check comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants