Repository navigation
Serialize keys for aggregation in chunks that fit in the CPU cache - #124955
Conversation
…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]>
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
|
Workflow [PR], commit [1041844] Summary: ✅
AI ReviewSummaryThis PR makes Findings❌ Blockers
Final VerdictChanges requested: fix the |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 of 43)
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
|
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]>
|
🕵 Merged master: it contains the revert of #123903, which caused the |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes318 object files changed (+244.47 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units2574 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. |
…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]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
Very reasonable.
…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]>
|
Measured on x86 with the whole condition removed ( 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
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 ClickBench Q39 (official 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. |
ClickBench queries Q17-Q19 (
GROUP BY UserID, SearchPhrase ...) run up to 20% faster withmax_block_size = 8192than 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_serializedaggregation method (HashMethodSerializedwith batch serialization). Before inserting the first key of a block into the hash table, it made several passes over the whole block:row_sizes);std::string_views of all keys (memories,serialized_keys);precomputed_hashes);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_sizeSampling the memory stalls showed that the extra stalls are in the serialization passes (
batchSerializeValueIntoMemory,collectSerializedValueSizes, the constructor ofHashMethodSerialized), and also in decompression and deserialization of the next block's columns, whose cache lines get evicted by these passes. An experiment that fedAggregator::executeOnBlockwith 8192-row slices of 65409-row blocks (copying the columns withcut) 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 toHashMethodSerialized.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,
getKeyHolderandgetPrecomputedHashadvance 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, andadaptiveKeyViewsAreBlockStablerelies on this) work as before. Rows that are never requested are not serialized at all.IColumn::batchSerializeValueIntoMemoryandbatchSerializeValueIntoMemoryWithNullgot the number of the first row to serialize (onlyIColumnHelperandColumnStringimplement 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):max_block_size = 8192GROUP BY UserID, SearchPhrase LIMIT 10... ORDER BY count() DESC LIMIT 10GROUP BY UserID, minute, SearchPhrase ...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, withprepared_keyspacked for the whole block in advance. The condition inshouldUseBatchSerializethat 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
GROUP BYby 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
26.10.1.2447-master(included in26.10and later)