Skip to content

Improve batched serialization for serialized aggregation - #91154

Draft
nickitat wants to merge 31 commits into
masterfrom
aljadljaldfj
Draft

nickitat wants to merge 31 commits into
masterfrom
aljadljaldfj

Conversation

@nickitat

@nickitat nickitat commented Nov 28, 2025 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Improves GROUP BY performance for multiple long string keys by serializing keys in cache-sized chunks during aggregation and merge instead of re-serializing each row individually.


Screenshot 2026-08-27 at 16 21 03 Screenshot 2026-08-27 at 16 20 44 Screenshot 2026-08-27 at 16 20 32 Screenshot 2026-08-27 at 16 20 15

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 28, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c2260fe]

Summary: ✅


AI Review

Summary

This PR reworks prealloc_serialized aggregation so ordered aggregation and merge loops can serialize long multi-string keys in cache-sized chunks, while non-ordered paths keep whole-block or row-at-a-time fallbacks. The current code fixes the earlier holder-lifetime and merge-path issues, but one important regression test is still missing and the PR metadata/evidence are not ready for merge.

PR Metadata
  • Changelog category: Performance Improvement matches the change.
  • Changelog entry: required for this category, but the current todo placeholder does not satisfy the template or changelog guidance. Exact replacement: Improves \GROUP BY` performance for multiple long string keys by serializing `prealloc_serialized` keys in cache-sized chunks during aggregation and merge instead of reserializing each row individually.`
Missing context / blind spots
  • ⚠️ The motivation is still unclear from the PR title/body: [WIP] Testing what happens if I remove IColumn::batchSerialize does not explain the intended user-visible contract, why only the prealloc_serialized paths are being changed, or what result would count as success.
Findings

⚠️ Majors

  • [tests/queries/0_stateless/05030_group_by_long_serialized_keys.sql:1] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/91154#discussion_r3864389259] The new correctness-sensitive logic here is the direct-arena compaction and EmplaceResult key re-pointing used by key-only serialized top-K pruning, but the added regression file never executes a GROUP BY ... ORDER BY ... LIMIT query without aggregates. 04910_group_by_top_k_long_serialized_erase_keys.sql still covers only the mapped count() shape, so the exact set-style path that now relocates keys can regress without any test going red. Suggested fix: add one focused long-key top-K regression without aggregate functions and compare the optimized and unoptimized results.
Tests
  • ⚠️ The Performance Improvement claim still has no before/after measurement in the PR discussion or CI. The only attached CI artifact is Build profile diff; add representative before/after numbers from tests/performance/group_by_long_serialized_keys* (at least one key-only and one mapped shape) so the claimed win and the row-width cutover are actually demonstrated.
Final Verdict

Needs changes before merge: the remaining blocker is evidence, not the core implementation. Add the missing key-only top-K regression, replace the placeholder changelog entry, and attach benchmark results for the claimed performance improvement.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 199/232 (85.78%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 28, 2025
@nickitat nickitat added the ci-non-blocking Do not block pipeline on too many failed tests label Nov 28, 2025
@alexey-milovidov alexey-milovidov changed the title [WIP] testing [WIP] Testing what happens if I remove IColumn::batchSerialize Nov 29, 2025
@nickitat
nickitat force-pushed the aljadljaldfj branch 2 times, most recently from 570e678 to 28d699d Compare November 30, 2025 16:33
@clickhouse-gh

clickhouse-gh Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

2 similar comments
@clickhouse-gh

clickhouse-gh Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@nickitat nickitat added the ci-performance performance only label Aug 22, 2026
nickitat and others added 11 commits August 22, 2026 20:04
…cates away

`HashMethodSerialized` with `prealloc` has two ways to produce a key. When the
block's serialized size fits in cache it serializes all of it column by column
into a scratch buffer, and the hash table copies every inserted key from there
into the arena. When it does not - rows of 128 bytes and up, or a block larger
than four times L2 - it falls back to a buffer allocated per row, serializes the
row into it, and again copies the key into the arena on insert.

That fallback pays a heap allocation and two writes per row, and it has no
serialized keys to precompute hashes from, so it also gets no prefetching.

Where the cells hold only the key - `GROUP BY` without aggregate functions -
nothing else allocates from the arena while a block is being aggregated, so the
keys can be written straight into it and handed to the hash table as they are.
An inserted key is then already in its final place; a duplicate leaves a hole,
and `commitKeyBatch` closes the holes by moving the kept keys down over them and
repointing their cells - the bytes of a key do not change, so neither its hash
nor its slot does - and gives the tail back to the arena. The block is done in
chunks of 512 KB, so that no thread needs one contiguous region for a whole
block and the compaction works on a region that is still in cache.

For the remaining per-row case - the same long keys with aggregate functions -
the per-row heap allocation is replaced by one buffer reused across the block.

Single thread, 10M rows, `GROUP BY` over two 100-byte string keys:

    distinct keys    without aggregates    with count()
             1000            -37%             -16%
           100000            -62%              -8%
          5000000            -37%              -9%

Peak memory is unchanged (+1.5 MiB for the chunk).

On aarch64 `shouldUseBatchSerialize` returns true unconditionally, so this
affects x86-64 only.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
…the loop commits

Two fixes on top of the previous commit, both found by measuring:

A caller that only probes with the keys - the adaptive aggregation kernels stage
a key per row and discard it - would never call `commitKeyBatch`, so the chunk it
allocated stayed in the arena for good. The batch is now off by default and a
loop that emplaces every row and commits afterwards turns it on with
`enableKeyBatch`, which is also what decides whether hashes are worth
precomputing. At 32 threads this alone was worth more than 20%.

The compaction no longer runs as a pass at the end of the chunk. A key that has
to move does so right after its own row is emplaced, while its cell is still hot
and no resize can have moved it - which also removes the cell array, the
resize detection and the lookup it needed when a two-level table had grown a
bucket in the meantime. The chunk is 128 KB rather than 512 KB, which keeps it in
cache while it is written, hashed and probed. Finally, the prefetch look-ahead is
measured once per block instead of once per chunk, where the measurement means
nothing.

20M rows, `GROUP BY` over two 100-byte string keys, best of 4, vs master:

    threads   100k keys   1M keys   5M keys
          1       -68%      -56%      -45%
          8       -37%      -11%      -10%
         16       -43%      -12%      -11%
         32       -32%       -3%       -1%

With `count()` - where only the reused per-row buffer applies - -6% to -23%.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
The 5M-key query needed more than 4.5 GiB and the smaller ones were dominated by
generating the data. These four run in about 0.2-0.5 s each and move by -10% to
-35% on this box.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
Giving the chunk's tail back is only sound while it is still the arena's last
allocation, which is what `enableKeyBatch` asks of its caller. Verified with a
temporary check compiled into the server - together with one that every repointed
cell really holds its row's key - across two-level, external, nullable,
multi-threaded, all-distinct, all-duplicate and tiny-block shapes.

The test now uses 100k rows instead of 200k, which covers the same key space, and
hashes the nullable keys through `ifNull` so that the `NULL` groups contribute to
the checksum instead of being skipped by `sum`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
…ates can use it too

The chunk of keys used to be carved out of the arena and its tail given back with
`Arena::rollback`, which only works while the chunk is the arena's last
allocation - true for key-only cells, false as soon as a new key's aggregate
state is allocated between one chunk and the next. So it was limited to `GROUP BY`
without aggregate functions.

The region takes that limitation away: a block's keys are laid out in a region
carved from the arena once and managed here. The kept keys sit at its front, the
next chunk is written directly after them - over the bytes of the rows that
turned out to be duplicates - and only when a chunk no longer fits is another
region taken from the arena. Nothing has to be given back, so nothing depends on
what else the arena is doing, and the methods whose cells carry a state are in.

`enableKeyRegion` still gates it, but on a much weaker promise than before: the
caller goes through the block's rows in order. That is what the two aggregation
kernels and the merge do, and what the adaptive aggregation kernels - which visit
rows in bucket-grouped order to stage them - do not.

20M rows, two 100-byte string keys, best of 3, vs master:

                        1 thread   16 threads
    GROUP BY, count()    -10..-19%   -14..-22%
    GROUP BY, no aggr    -48..-69%   -16..-39%

ClickBench Q16/Q17 are unchanged: their keys are short enough that batch
serialization keeps them, which this does not touch.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
…ones a region

`HashMethodSerialized` with `prealloc` only serialized a block's keys in one
column-major pass while `total_size <= 4 * L2` and the average row was under 128
bytes; outside that it serialized row by row into a buffer of its own. The
threshold does not hold up: on this box the one-pass form is 2.5-4x faster than
the per-row one exactly where the threshold rules it out - long keys, or short
keys in a large block - and never slower where it does not. aarch64 has been
taking the one-pass form unconditionally all along, with the same reasoning
attached to it, so both architectures now do.

On top of that, where the cells hold only the key, the block is serialized into a
region of its own instead of a buffer that every inserted key is then copied
from. The kept keys stay where they were written, the next chunk of rows is
written over the bytes of the rows that turned out to be duplicates, and only
when a chunk no longer fits is another region taken from the arena. Where the
cells also hold an aggregate state this does not pay: the copy puts a new key in
the arena right in front of its state, and keeping those two together on a page
is worth more than the copy costs.

20M rows, `GROUP BY` over two string keys, best of 3, vs master:

    key bytes  block rows  aggregate  1 thread  16 threads
          100       65505    count()      -67%        -29%
          100       65505       none      -66%        -16%
          100     1000000    count()      -64%        -37%
          100     1000000       none      -67%        -47%
           20     1000000    count()      -73%        -58%
           20     1000000       none      -73%        -59%
          300       65505    count()      -39%         +8%
          300       65505       none      -39%         +1%
           20       65505    count()       -4%        -11%
            8       65505       none       -1%         +1%

`IColumn` gains a row-range form of `batchSerializeValueIntoMemory`, which is
what lets the region serialize a chunk at a time without the per-row virtual call.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
Measuring `group_by_multiple_strings`, the test the size heuristic was added with,
showed that dropping that heuristic outright regresses its widest shape badly:
1024-byte rows went +28% at one thread and +72% at 32. Laying a block out one key
column at a time writes it with a row-sized stride, and that stops paying once a
row is much wider than a cache line - which is what the heuristic's `avg_row_size`
half was guarding. Only its `total_size <= 4 * L2` half is wrong, and that half is
now gone.

So batch serialization keeps the row-size bound, and the key region gets its own,
measured the same way: it wins -72% at 128 bytes per row, -21% at 192, -9% at 512
and nothing beyond, so it stops at 512.

Where a row is too wide for either, the keys are still serialized one row at a
time - but into a buffer reused across the block, which is why those shapes end up
faster than before rather than merely unchanged.

3M rows, `GROUP BY` two string keys, vs master:

    row bytes  aggregate   1 thread   8 threads   32 threads
          128    sum()        -26.0%      -35.4%       -30.8%
          128    none         -31.0%      -21.4%       -26.1%
         1024    sum()        -12.0%      -14.5%        -8.5%
         1024    none         -11.4%      -14.5%       -15.3%
     16 .. 64    both          within noise

20M rows in 1M-row blocks, which the size rule used to exclude:

    row bytes  1 thread  16 threads
           20    -76.5%      -58.3%
           40    -75.3%      -55.5%

`aggregate_with_serialized_method`: -17.6% and -10.0% on the string-key queries,
the rest unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
Same wording as on `serialized-keys-batch-threshold`: shrinking a regressing
long-row block 64 times, from 65536 rows to 1024, only takes it from +29% to
+16%, while the row size decides the sign on its own.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
Same measurement as on `serialized-keys-batch-threshold`: with the row-size rule
applied on Graviton4 instead of the shortcut, every shape from 32 to 1024 bytes
per row stayed within +-3% of master, so the shortcut stays.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
The one-pass serialization was done in the constructor, so the decision had to be
made there too - before `enableKeyRegion` tells the state whether the caller will
read the keys from a region instead. That forced `can_use_key_region` to turn the
one pass off for everyone, including the callers that never opt in: the adaptive
aggregation kernels, which ask for one key at a time to probe with, were left
serializing row by row.

The pass now runs on the first key asked for, so `enableKeyRegion` can switch the
mode with nothing serialized yet, and a caller that does not opt in still gets the
one pass. It also means a block whose keys are never asked for is never
serialized.

Measured on `hits` and on synthetic shapes, this is performance-neutral on its own
(within +-4%). What it fixes is a measurement trap: with the decision made up
front, an experiment that merely allowed the region for a method silently took the
one pass away from the probe path, which read as a 16-26% regression that had
nothing to do with the region.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
nickitat and others added 6 commits August 23, 2026 19:40
… a time

The block's keys were laid out one key column at a time into a buffer holding the
whole block, or - above a row-size threshold, and never on aarch64 - one row at a
time. Measuring the two layouts against each other on the same binary shows the
whole-block form is the wrong default on both architectures once rows are wide:

    row bytes         256    512   1024   2048   4096
    aarch64 t=1     +12.8% +27.5% +34.2% +28.7% +13.8%
    aarch64 t=32    +51.5%      -  +52.3%      - +16.4%
    x86-64  t=1     +11.2% +16.9% +26.3% +41.7% +37.1%

So the aarch64 shortcut, which pinned that architecture to the whole-block form
whatever the row size, goes, and the row-size threshold applies to both.

What makes the whole-block form lose is that it writes the block to memory and
reads it back; the cost tracks the buffer, from +6.6% at 128 KiB to +27% at 32 MiB.
Laying out a 128 KB chunk at a time keeps that in cache and keeps the one pass'
advantage over the row-at-a-time form, which is that the per-row call amortises
over a whole key column. So the whole-block buffer is gone: a caller that goes
through the rows in order gets the chunk, and one that does not gets a row at a
time.

Against the previous rule, GROUP BY with sum() over two string keys:

    x86-64, rows < 128 B    -1.4%..-8.7% at one thread, -26%..-39% at 32
    aarch64, all row sizes  -3%..-31%

Key-only cells keep the chunk up to 512 bytes per row rather than 128, because
there it is also where the keys stay - an inserted key is not copied into the
arena at all.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
Chunking a block that is already small only adds the per-chunk work: 40-byte rows
went +3% to +13% at one thread on all three boxes. Below 4 MiB the block is laid
out in one piece, which is what it was before, and above it the chunk keeps the
pass in cache.

Co-Authored-By: Claude Opus 5 <[email protected]>
Laying a small block out in one chunk is right only where the chunk is a buffer
reused across chunks. Where the cells hold only the key the chunk is also where
those keys stay, and one chunk per block leaves the bytes of every duplicate row
behind instead of letting the next chunk write over them - measured on Intel, that
cost 29-32% at one thread on 40 and 56 byte rows.

Co-Authored-By: Claude Opus 5 <[email protected]>
…paying

The test covered one row width. The layout decision turns on that width, so it now
walks it from 40 to 1024 bytes per row, with and without an aggregate function -
the cells hold only the key without one, which changes where the keys are laid out
and whether an inserted key is copied.

The narrow shapes are the ones to watch: measured against master they are where the
chunked layout stops paying (+5% to +28% at 40 and 56 bytes per row, depending on
the machine), while everything from 112 bytes up wins by 4% to 63%.

Each width also gets a single-thread copy. With one thread per core the difference
between the layouts is largely hidden - on the same shape it is +28% at one thread
and +2% at 32 - so without these CI would measure the flat half of the picture.

18 queries, about 7 seconds a pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
@nickitat nickitat removed the ci-performance performance only label Aug 23, 2026
`adaptiveKeyViewsAreBlockStable` asked for `use_batch_serialize`, which went away
with the whole-block gate, so its `requires` stopped matching and it answered
`true` for every state - including the ones whose views do not survive the row
they came from. The count kernel then kept `last_staged_key` pointing into
scratch that the next row, or the next chunk, writes over. Two consecutive staged
misses whose hashes collide would have merged into one record, and the collision
is the only thing standing between that and a wrong count, which is why nothing
caught it.

The state answers for itself now, and the layouts differ: the block laid out in
one piece and the chunk that is the keys' home in the arena are stable, the chunk
that is a reused buffer and the row-at-a-time scratch are not. Asking settles the
layout if the first key has not already, because the answer depends on it. A
method that has no such choice keeps answering `true` through the same `requires`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XK6uvyssdB3uUmju6uZYxp
@nickitat nickitat added ci-performance performance only and removed ci-performance performance only labels Aug 24, 2026
Three ways the region reached past what it had prepared.

`executeImplBatch` turned the region on before the branch, and the `no_more_keys`
branch looks a row up with `findKey`, which consults the row's hash before it has
taken a key holder - so with the region on, no chunk had been prepared, the
serialized keys were empty and `precomputed_hashes` had nothing in it at all. The
region now goes on inside the branch that emplaces, and `findKey` and
`emplaceKey` both check that the row is one the method has prepared before
reading its hash, so the ordering cannot bite again from a new caller.

The look-ahead was bounded by the size of `precomputed_hashes` rather than by the
part of it a chunk has filled, so the last rows of every chunk prefetched on
whatever `resize` had left in the array. `precomputed_hashes_end` records the
chunk's end and bounds both reads. The values only ever reached `prefetchByHash`,
which is why nothing failed, but they were uninitialised reads all the same.

`region_end - region_free` ran before either pointer was set, on the first
key-only chunk of a block; subtracting one unset pointer from another is not the
zero it resembles. The first chunk now takes the `!region_free` branch instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XK6uvyssdB3uUmju6uZYxp
@nickitat nickitat removed the ci-performance performance only label Aug 24, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
Laying a block's keys out ahead of the probe loop pays for itself as soon as
the probe misses, at any row width: from 13 thousand keys on it is worth
20-50% out to 1024 bytes per row. Against a table small enough to stay in
cache it buys only the batch serialization, and past about 500 bytes per row
writing the row out and reading it back costs more than that. At a thousand
keys on Zen5 the layout still gains 8% at 320 bytes per row, breaks even at
528, and loses 10-22% at 1040 - which is the shape `group_by_multiple_strings`
measures, and where it regressed:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=91154&sha=73adc5ad5e68c737ab8de831053f8c2ae51d0639&name_0=PR
#91154

So the layout is skipped only where both bounds hold: the table is at most
256 KiB and a row is at least 512 bytes. Everything else keeps it, including
the 13 thousand key shapes an L2-sized table bound would have caught.

Measured against the same commit without the gate, medians of 15 runs with an
A/A control, on Zen5 (EPYC 9R45), Granite Rapids (Xeon 6975P-C) and
Graviton4: `group_by_multiple_strings` with 512 byte keys recovers 5.6-31%
on Zen5, 12-13% on Granite Rapids and 2-9% on Graviton4; its 64 byte keys and
all 18 queries of the serialized-key perf tests stay within the control.
`mergeStreamsImplCase` turned the key region on for the set variant only. Its
two siblings - the mapped one, and the counts-only one in `mergeStreamsImpl` -
walk a block's rows in the same order, so they can prepare its keys ahead of
their loops as well. The `no_more_keys` branches still may not: they look a
row up without taking a key holder first, so they would ask for the hash of a
chunk nobody has prepared.

Came out of review of #91154
@nickitat nickitat added ci-performance performance only and removed ci-performance performance only labels Aug 25, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
`executeImplBatch` keeps a loop of its own for a bare `count()`, and it returns
before the general loop that opts into the key region. So a plain
`GROUP BY ... count()` was left on the old layout choice: once a row is too wide
for the whole-block path, it fell back to serializing a row at a time and never
got the chunked layout - on one of the shapes this work is meant to speed up.

The same opt-in goes there, with the same exclusion for `no_more_keys`, which
looks a row up without taking a key holder first. The all-const-keys branch
beside it emplaces a single row, so there is nothing to lay out.

Measured on Zen5 against the same commit without this, 100 thousand keys at 616
bytes per row, medians of 11 runs with an A/A control: -42.7% at one thread, and
-17.6% at 16 threads with the adaptive aggregator off. With it on, its own
kernels take a block that size over at that width, so nothing changes there. The
other 17 queries of the serialized-key performance tests stay within the control.

Came out of review of #91154
Comment thread src/Common/ColumnsHashing.h Resolved
The region a chunk is laid out in is taken from the arena in one piece, and only
the rows that turn out to be new keys keep their bytes - the rest is written over
by the rows that follow, and whatever the block never reaches is simply left
behind. A block that inserts nothing therefore left a whole region behind, and
since a fresh state starts a fresh region, what a key-only aggregation held grew
with the number of blocks that went past it rather than with the keys it found.

Measured on Zen5, a thousand keys of 216 bytes read from 20 million rows on one
thread: 402 MiB at 65536-row blocks, 1282 MiB at 16384, and 4994 MiB at 4096 -
about a megabyte per block, for a table that needs a few hundred kilobytes. With
the tail given back: 25, 12.9 and 8.8 MiB, and the same time or a little better.

The arena hands memory out by bumping a pointer, so the tail can go back only
while it is still the last thing handed out. That holds today - a region is only
used where the cells hold no aggregate state, so nothing else takes from that
arena between one chunk and the next - but `Arena::position` is asked rather than
assumed, which keeps the rollback honest if that ever changes.

Came out of review of #91154
Comment thread src/Common/ColumnsHashing.h Resolved
…holder

`keyViewsAreBlockStable` answered yes for the serialized method that serializes a
row at a time, on the grounds that the key goes into the arena. It does, but it
stays there only if the row inserts: `SerializedKeyHolder` is discarded by rolling
the arena back, which is what a lookup that finds its key does - and what the
adaptive count kernel does with every key it stages.

That kernel keeps the last staged key to tell a run of equal misses from two
misses that merely share a hash. With the view rolled back under it, the next row
serializes over the same bytes, the comparison sees itself and says the run
continues, and two different keys behind one hash collapse into a single staged
record - which is exactly the case the comparison is there to catch, so the
multiplicities it publishes would be wrong.

The predicate now says no, and the kernel already refuses to seed its run
tracking with a view it was told is unstable.

Measured on Zen5, `GROUP BY` with `count()` over two `Dynamic` keys of 20 million
rows, medians of 9 runs against an A/A control: at a thousand keys +0.3% and
-1.8%, at a million +0.4% and -2.9%, at one and eight threads - all inside the
control, and the counts agree group by group.

Came out of review of #91154
Comment thread src/Common/ColumnsHashing.h Resolved
`prepareKeyChunk` re-armed the lazy hash init for every chunk, on a condition
that is a compile-time constant, so `initPrecomputedHashes` ran per chunk even
where the precomputed-hash mode was off - the caller asked for no prefetch, or a
chunk found the table small enough to trip `min_bytes_for_prefetch`, which turns
the mode off for the rest of the block. Nothing reads those hashes then: the
probe hashes every row again. Now the chunk only asks for them while they are
still read.

In the default configuration this changes nothing measurable: the 18 queries of
the serialized-key performance tests stay within +-3.7% of the same commit
without it, medians of 11 runs.

With `enable_software_prefetch_in_aggregation = 0` it is a trade, because the
pass that looked dead was hiding probe stalls. One build, the two behaviours
switched at run time, 20 million rows over 1.3 million keys of 216 bytes:
-4.9% at one thread, +5.5% at eight and sixteen, +10.1% at thirty-two. `perf
stat` says why - the version doing 12% more instructions spends 25% fewer
cycles, at the same miss count (IPC 1.13 against 0.76). Sweeping the chunk with
prefetch instructions instead, either over its bytes or over its key views, does
not reproduce it, so it is the work that pays, not the touching. A query that
turns the prefetch off is asking for no prefetching, and this leaves it that way
rather than keeping a hash pass as one in disguise.

Came out of review of #91154
Against a table that stays in cache the layout buys only the batch serialization,
and past some row width writing the row out and reading it back costs more than
that. The bound was set at 512 bytes from the width where Zen5 and Granite Rapids
cross over, and the machine the performance tests run on does not agree: it has
been losing 11-19% on `group_by_multiple_strings` with its 64 character keys - a
thousand keys of 144 bytes - at every thread count and on every commit since the
layout rule landed:

  ebe078b  +13.3% (2 threads)  +12.6% (4)  +12.1% (8)  +11.2% (16)
  73adc5a  +13.6% (4)  +10.5% (8)  +12.4% (16)  +12.0% (32)
  8af5e81  +17.4% (1)  +18.6% (2)  +15.9% (8)
  https://s3.amazonaws.com/clickhouse-test-reports/PRs/91154/8af5e81646cd92b787bada7154a388dd95d9c643/performance_comparison_amd_release_master_head_4_6/report.html

So the bound goes to 128 bytes, the same width the whole-block layout is bounded
by: a cache-resident table keeps the layout only while its rows are narrow enough
that no machine argues about it. This gives up a win rather than splitting the
difference - measured on Zen5, the same shape loses 6-12% by being gated, medians
of 15 runs with an A/A control - but a bound that only one machine is happy with
is not a bound.

Nothing else moves: the 18 queries of the serialized-key performance tests stay
within +-2.4% of the same commit without this, and the 512 character keys of
`group_by_multiple_strings`, which the gate already caught, are unchanged.

#91154
Comment thread src/Common/ColumnsHashingImpl.h Resolved
`findKeyImpl` remembered the key the caller handed it, and `findKey` now hands
that key back when the holder borrowed it from the arena. What the cache holds
could then be written over by the next row of the same size, and answer for it.

Nothing reaches that today. The only method whose holder rolls the arena back is
the serialized one, and it is built with the consecutive-key cache switched off
(`HashMethodBase<Self, Value, Mapped, false>`); every method that does cache -
one number, string, packed string, fixed string - hands out keys pointing into
the block's own columns, which outlive the row, and their holders give nothing
back. Two attempts to make it answer wrongly, a `no_more_keys` `GROUP BY` over
`Dynamic` keys with the cache forced on and consecutive keys made to differ,
returned exactly what the reference and the cache-off run did, as they must.

Still, the two paths should not disagree about what is safe to remember. A hit is
now remembered through the cell, which is where `emplaceImpl` has always read it
from and which stays for as long as the table does. A miss has only the row's own
key to remember, so it is remembered only where that key outlives the row - the
serialized methods answer that for themselves, everyone else says yes, and where
the cache is compiled in the answer folds to a constant.

Measured against the same commit without it: the 18 serialized-key performance
queries within +-2.6%, `group_by_multiple_strings` within its noise, and the
functional tests unchanged at 411 passed with the same 135 missing-config
failures.

Came out of review of #91154
@nickitat nickitat changed the title [WIP] Testing what happens if I remove IColumn::batchSerialize Improve batching serialization for serialized aggregation Aug 27, 2026
@nickitat nickitat changed the title Improve batching serialization for serialized aggregation Improve batched serialization for serialized aggregation Aug 27, 2026
@abashkeev abashkeev added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 3, 2026
@snelheidai

Copy link
Copy Markdown

Forcing whole-block batching of serialized keys buys −8.1% on TPC-DS query_47 and −5.4% on query_57, but costs query_22 +18.3% and 29% more peak memory. So the width gate is protecting a real effect, and collecting that gain needs the cache-sized chunking this PR does rather than a wider gate.

On x86, HashMethodSerialized::shouldUseBatchSerialize() batches only when a block fits 4×L2 and average key width is under 128 B, so wide-key aggregations serialize every block row by row — which also gives up the precomputed hashes and prefetching that exist only for batch-serialized keys. To price that path I replaced the gate with a plain byte budget set high enough to always batch (a local gate relaxation, no chunking):

query row-wise → whole-block delta A/A null peak memory
query_47 3471 → 3190 ms −8.1% −1.8% 304 → 323 MiB
query_57 1796 → 1699 ms −5.4% −0.2% 335 → 369 MiB
query_22 2082 → 2463 ms +18.3% +0.05% 147 → 189 MiB
query_23 6370 → 6415 ms +0.7% +0.05% 2141 → 2317 MiB

Profile counters confirm the path actually switched: query_47 goes from 0 batch / 2651 row-wise blocks to 2653 / 0, query_57 from 0 / 880 to 880 / 0. query_23's blocks were already batched in both arms, so it works as a second control beside the A/A null. An earlier tiled variant of mine regressed query_22 by 13.2%, so two independent whole-block implementations hit the same failure mode on that query.

Setup: ClickHouse's shipped tests/benchmarks/tpc-ds definitions at SF10, adapted, so this is not an audited TPC-DS result; single server on 4 vCPU Xeon 8375C, warm, 4 interleaved paired reps with the first discarded; one binary serving both arms (master 1e93c0a2 plus two unrelated local patches, ColumnsHashing.h unchanged on master since) so only the setting differs; full ordered answers byte-identical per arm.

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

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

ci-non-blocking Do not block pipeline on too many failed tests comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants