Skip to content

Serialize keys for aggregation in chunks that fit in the CPU cache - #124955

Merged
alexey-milovidov merged 6 commits into
masterfrom
aggregation-serialized-keys-in-chunks
Oct 15, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
aggregation-serialized-keys-in-chunks

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

ClickBench queries Q17-Q19 (GROUP BY UserID, SearchPhrase ...) run up to 20% faster with max_block_size = 8192 than with the default 65409, see #124791 (comment). This PR finds the reason and gets the gain without changing the block size.

The reason

These queries use the prealloc_serialized aggregation method (HashMethodSerialized with batch serialization). Before inserting the first key of a block into the hash table, it made several passes over the whole block:

  1. computed the sizes of the serialized keys of all rows (row_sizes);
  2. computed the pointers and std::string_views of all keys (memories, serialized_keys);
  3. serialized every key column into the buffer of all keys;
  4. computed the hashes of all keys (precomputed_hashes);
  5. and only then probed the hash table row by row, reading the keys and hashes again.

For 65409 rows this is ~40 bytes per row of temporary arrays plus the keys themselves, several MB per thread. That's more than the L2 cache (2 MiB per core on the Graviton4 where I measured), so every pass re-reads the previous pass's output from L3. With one thread it fits in L3, and with a few threads the effect is small. With 96 threads each core gets ~375 KB of the 36 MB L3, so the passes go to the main memory.

Hardware counters for Q18 on 96 threads, with the same instruction count at both block sizes:

max_block_size cycles last level cache read misses backend stall cycles on memory
8192 10.4G 65M 1.0G
65409 13.5G 163M 4.5G

Sampling the memory stalls showed that the extra stalls are in the serialization passes (batchSerializeValueIntoMemory, collectSerializedValueSizes, the constructor of HashMethodSerialized), and also in decompression and deserialization of the next block's columns, whose cache lines get evicted by these passes. An experiment that fed Aggregator::executeOnBlock with 8192-row slices of 65409-row blocks (copying the columns with cut) removed the stalls and the difference as well. So reading in big blocks is not the problem, only this part of the aggregation is. The same experiment slowed down other methods because of the copying, which is why the fix is local to HashMethodSerialized.

The change

The keys are serialized, and their hashes computed, lazily, in chunks of consecutive rows that take an eighth of the L2 cache (64 KiB - 1 MiB), right before they are needed. The prefetch look-ahead, getKeyHolder and getPrecomputedHash advance the "serialized up to" frontier. Every row is serialized once into the same buffer as before, so the keys stay valid for the whole block: callers that access rows out of order (the adaptive aggregator publishes its staged rows grouped by bucket, and adaptiveKeyViewsAreBlockStable relies on this) work as before. Rows that are never requested are not serialized at all.

IColumn::batchSerializeValueIntoMemory and batchSerializeValueIntoMemoryWithNull got the number of the first row to serialize (only IColumnHelper and ColumnString implement them).

Results

ClickBench hits (100M rows), aarch64 Neoverse-V2, 96 cores, server-side query duration, best of 16 runs (the machine was shared with other workloads, so the noise is a few percent):

Query before after before, with max_block_size = 8192
Q18 GROUP BY UserID, SearchPhrase LIMIT 10 75 ms 47 ms 60 ms
Q17 ... ORDER BY count() DESC LIMIT 10 168 ms 158 ms 133 ms
Q19 GROUP BY UserID, minute, SearchPhrase ... 271 ms 281 ms 235 ms

Other queries didn't change (all 43 queries were compared by cycles). Q18 also executes 14-25% fewer instructions, because the rows skipped by the aggregation are not serialized anymore. With a single thread Q17 and Q19 execute 1-2% more instructions (the frontier checks), and there was no cache problem to fix there.

Q17 and Q19 go through the frozen path of the adaptive aggregator (executeFrozenImpl), which stages all missed keys of a block and publishes them once per block (publishDelayedRecords → buildDeduplicatedCountChunk). Most of their remaining stalls are there: the same whole-block multi-pass pattern, which this PR doesn't change. HashMethodKeysFixed (keys128, Q33) has the same pattern too, with prepared_keys packed for the whole block in advance. The condition in shouldUseBatchSerialize that disables batch serialization on x86 for blocks larger than 4 × L2 can probably be removed now, but I could not measure on x86.

A test compares the results of aggregation by serialized keys (also Nullable, also very long keys that make chunks of a single row, also through the adaptive aggregator) for different block sizes; the reference was generated by the binary without this change.

Related: #124791

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY by several keys, which requires the serialization of keys, serializes the keys of a block in chunks that fit in the CPU cache instead of all at once. This makes such queries faster when many threads are used, for example, ClickBench Q18 is 37% faster on a 96-core machine.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2447-master (included in 26.10 and later)

alexey-milovidov and others added 2 commits October 9, 2026 15:48
…at fit in the CPU cache

`HashMethodSerialized` with batch serialization (the `prealloc_serialized` aggregation method)
serialized the keys of all rows of a block into a buffer, and then computed the hashes of all of them,
before inserting the first key into the hash table. For a block of 65409 rows these temporary arrays
take several megabytes per thread, so every pass over them misses the L2 cache, and with many threads
they don't fit into the shared L3 cache either.

Now the keys are serialized and hashed in chunks of consecutive rows (an eighth of the L2 cache),
right before they are used. Every row is still serialized once into the same buffer, so the keys stay
valid until the end of the block. `IColumn::batchSerializeValueIntoMemory` got the number of the first row.

Related: #124791

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lized-keys-in-chunks

# Conflicts:
#	src/Columns/ColumnString.cpp
#	src/Columns/ColumnString.h
#	src/Columns/IColumn.cpp
#	src/Columns/IColumn.h
#	src/Common/ColumnsHashing.h
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1041844]

Summary: ✅


AI Review

Summary

This PR makes HashMethodSerialized serialize and hash GROUP BY keys lazily in cache-sized chunks, and it threads a start_row through batched column serialization so adaptive remainder paths no longer restart from row 0. The main cache-locality change looks sound, but the touched LowCardinality(String) fast path still treats dictionary indexes as 1-based, which makes empty-string/default entries read before the ColumnString offsets array during key serialization.

Findings

❌ Blockers

  • [src/Columns/ColumnLowCardinality.cpp:378] LowCardinality(String) reserves dictionary slot 0 for the nested default value, and ColumnUnique::uniqueInsertData reuses that slot when the value bytes equal the default (for String, that is ''). The fast path here then evaluates offsets[index - 1], so grouping by LowCardinality(String) with an empty-string key reads before the offsets array while serializing the key. collectLowCardinalityStringSizes has the same assumption at src/Columns/ColumnLowCardinality.cpp:406, so fixing only the serializer is not enough. Handle index == 0 explicitly in both helpers; the first string starts at byte offset 0.
Final Verdict

Changes requested: fix the LowCardinality(String) default-index handling before merge.

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

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes how keys are serialized and hashed for multi-key GROUP BY with string keys: instead of doing a whole block up front, it now works in cache-sized chunks. Neither flagged ClickBench query clearly goes through that path. Q34 (-5.4%) groups on a single URL key, so it is downgraded to not_sure. Q28 (-5.7%) stays not_sure because the two tests disagree and the measurements were noisy. Both queries used about the same CPU time before and after (about 1% less), and the ClickBench queries that do group on several keys including strings, which should see any benefit, were not flagged, so this run shows no measurable effect from the PR in either direction. The PR runs for both benchmarks also shared one machine, which adds some uncertainty to the small deltas.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1050 990 -5.7% <0.0001 aggregation: This GROUP BY has a single key, so it should not use the multi-key serialized hashing path that the PR changes into chunks. CPU time is about the same, so the -5.7% shift is not work-backed.
⚠️ 34 not_sure 1020 965 -5.4% <0.0001 aggregation: The query groups on a single URL string key, which takes the plain string-key path and not the serialized multi-key path changed here. CPU time is about the same and the query's history is noisy, so the -5.4% looks like normal variation.

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: b00168d3-f6bb-402d-90a9-646948fabb98
  • MIRAI run: 94bb4dc5-ec6b-4118-8680-f7aa284d85b9
  • PR check IDs:
    • clickbench_901590_1791740075
    • clickbench_901596_1791740075
    • clickbench_901602_1791740075
    • tpch_adapted_1_official_901612_1791740075
    • tpch_adapted_1_official_901624_1791740075
    • tpch_adapted_1_official_901661_1791740075

alexey-milovidov and others added 2 commits October 10, 2026 13:46
The performance test `aggregate_with_serialized_method` showed up to 17%
slowdown on aarch64. `serializeNextChunk` walked the rows of a chunk twice
(once to find its end, once to fill the offsets and `memories`), and
`getSerializedKey` had to combine an offset with `row_sizes`. Now the
chunk is assembled in one pass and the keys are stored as
`std::string_view`, as before the chunking. On a Neoverse-V2, the extra
instructions over master in the queries of this test went from 5-6% to
1.5-3%, and the cycles are within noise of master.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124955&sha=e24adaa80c4ed6e066ca85126c1d3e024581952b&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%205%2F6%29
#124955

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

Copy link
Copy Markdown
Member Author

🕵 Merged master: it contains the revert of #123903, which caused the 05243_query_condition_cache_top_k_parquet failures in all stateless jobs. Added e62c867 for the aggregate_with_serialized_method slowdown on ARM (up to +17%): serializeNextChunk now builds each chunk in one pass over the rows instead of two, and stores keys as std::string_view again. Measured on a Neoverse-V2 with perf stat: the extra instructions over master in that test dropped from 5–6% to 1.5–3%, and cycles are within noise of master. schema_inference_text_formats (no aggregation) and the Docker image pre-pull failure in Integration tests (arm_binary, 2/4) are unrelated.

Comment thread src/Common/ColumnsHashing.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1041844db with master 1b9d29136 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

318 object files changed (+244.47 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 23.34 MiB 23.55 MiB +216.83 KiB (+0.91%)

719 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

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

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

Job report

…ted range

`HashMethodSerialized` started the first chunk of serialized keys at row 0, so
when a fresh state aggregates only a tail of a block (the remainder after an
adaptive aggregation split, in `executeImpl` or `executeFrozenImpl`), the rows
before it were serialized needlessly. Add `skipRowsBefore`, called with
`row_begin` by the aggregation kernels, so the first chunk starts at the first
requested row.

Address review: #124955 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Very reasonable.

@alexey-milovidov alexey-milovidov self-assigned this Oct 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 15, 2026
Merged via the queue into master with commit 3462415 Oct 15, 2026
173 checks passed
@alexey-milovidov
alexey-milovidov deleted the aggregation-serialized-keys-in-chunks branch October 15, 2026 04:35
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
…ull-map-byte-is-a-predicate

Conflict in `IColumn.cpp`: master made `batchSerializeValueIntoMemoryWithNull` serialize a
sub-range of rows (`start_row`, ClickHouse#124955); kept that shape and the canonical `is_null[row] != 0`
key byte.

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

Copy link
Copy Markdown

Measured on x86 with the whole condition removed (shouldUseBatchSerialize() returning true, so both the 4 × L2 block bound and the 128-byte average-width bound are gone): TPC-DS query_47 and query_57 got 5-6% faster, but query_22 got 10% slower and used 22% more peak memory. The block bound alone was not isolated; see the last paragraph.

Setup: Xeon Platinum 8375C, 4 vCPU (2 cores × 2 threads, 1.25 MiB L2 per core), master 8b903d1 vs. the same commit with that one-line change. TPC-DS SF10 with the queries and settings.json from tests/benchmarks/tpc-ds (not an official TPC-DS result), default max_threads, fresh server per cycle and arm, hot time = min of runs 2-3, 4 ABBA cycles; the change is the geometric mean of the per-cycle ratios with a bootstrap CI. Query results were identical. With 4 vCPUs this does not reproduce the many-thread L3 pressure behind this PR.

Query master, median ms condition removed, median ms change (95% CI) peak memory
query_47 3444 3274 -5.4% (-7.1 .. -3.6) +5%
query_57 1875 1769 -6.1% (-7.0 .. -5.1) +8%
query_67 9491 9251 -2.4% (-3.5 .. -1.4) +8%
query_11 1754 1716 -2.4% (-3.5 .. -1.2) +4%
query_22 1536 1697 +10.4% (+10.1 .. +10.7) +22%

query_23 a/b (already batched on master) did not change; query_39 a/b (~360 ms) were too noisy in 4 cycles to show anything.

query_22 groups by four Nullable(FixedString(50)) columns (204 B per row), and over 99% of its probes hit an existing key (51K groups over 26.6M rows). With the condition removed, IColumnHelper<ColumnFixedString>::batchSerializeValueIntoMemoryWithNull takes 14.7% of samples, against 6.1% for the per-row serializeValueIntoMemoryWithNull on master (user CPU +10.5%): writing wide keys out column by column into the chunk and reading them back costs more than it saves when nearly every probe hits. The whole-block version of the same experiment in September gave query_22 +18.3% (query_47 -8.1%, query_57 -5.4%; comment on #91154), so chunking roughly halved this penalty but did not remove it.

ClickBench Q39 (official hits load, keys of about 190 B, 10 ABBA cycles) did not change: 119.5 vs. 118.8 ms, paired ratio 1.03 (95% CI 0.99-1.10). The batch passes cost about what the per-row serialization saved, e.g. 3.4% of samples in the generic IColumnHelper<ColumnVector<UInt16>>::batchSerializeValueIntoMemory.

Every query that changed has average keys of at least 128 B, so the width bound is what disables batching for them, and removing only the 4 × L2 bound would not change them. That bound alone matters only for keys averaging under 128 B in blocks larger than 4 × L2: on this CPU, 65409-row blocks with 80-128 B keys. With 2 MiB of L2 per core it cannot apply to blocks of up to 65536 rows.

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

Labels

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.

3 participants