Skip to content

Use HashSet for aggregations without aggregates - #108862

Merged
nickitat merged 33 commits into
masterfrom
void-mapped-groupby
Aug 19, 2026
Merged

nickitat merged 33 commits into
masterfrom
void-mapped-groupby

Conversation

@nickitat

@nickitat nickitat commented Jun 29, 2026 •

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):

Aggregation queries without aggregate functions now use HashSet-based methods instead of HashMap (for supported key types). Speedups up to 1.8x times were observed.


Screenshot 2026-07-03 at 00 34 25

Further steps are distinct -> group by rewrite and key-columns-only (and perhaps semi) joins.


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

Version info

  • Merged into: 26.8.1.1709 (included in 26.8 and later)

nickitat and others added 2 commits June 29, 2026 21:20
For `GROUP BY <single UInt64>` with no aggregate functions (effectively
`DISTINCT`), the Aggregator stores an `AggregateDataPtr` per key only as a
`0x1` occupancy sentinel - dead weight that doubles the cell size.

This adds `AggregatedDataVoidCell`: an 8-byte cell that stores only the key
but still advertises `mapped_type = AggregateDataPtr` by routing `getMapped`
to a `thread_local` dummy. All shared Aggregator code that binds
`AggregateDataPtr &` to `getMapped` compiles and runs unchanged, and the
parallel two-level merge is race-free (`dst`/`src` alias the same per-thread
dummy; with zero aggregate functions nothing is read from it). The method
disables `consecutive_keys_optimization` because the keys cache assumes a
`value.second` that a key-only cell does not have.

New `key64_void` / `key64_void_two_level` variants are selected when
`aggregates_size == 0` and the single key is a non-nullable UInt64.

Microbenchmark and end-to-end results (release, same binary A/B via the
`CH_NO_VOID` env gate, max_threads=16): `numbers_mt GROUP BY number` runs
1.4-1.8x faster with ~2x less peak memory; scattered bijective keys 1.3x;
never slower.

PROTOTYPE: covers only single non-nullable UInt64; the `CH_NO_VOID` env gate
and the thread_local-dummy aliasing are temporary scaffolding for A/B.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nickitat nickitat added pr-performance Pull request with some performance improvements ci-performance performance only labels Jun 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [338fac2]

Summary: ✅


AI Review

Summary

This PR switches supported no-aggregate GROUP BY / DISTINCT paths from map-backed aggregation tables to HashSet-backed ones, and wires the void-mapped methods through two-level conversion, parallel merge, adaptive aggregation, and the external-merge _hash64 upgrade. The current code looks coherent and the PR already has credible performance evidence, but one material correctness path is still missing focused regression coverage before this should merge.

Tests
  • ⚠️ [tests/queries/0_stateless/04926_nullable_void_keys_better_hash_external_merge.sql:1] The new spill coverage only exercises the nullable fixed-width _void_hash64 methods. Aggregator::mergeBlocks now also upgrades serialized_void, nullable_serialized_void, prealloc_serialized_void, and nullable_prealloc_serialized_void to dedicated _hash64 variants, which is a separate correctness path because it relies on saved hashes plus arena-backed serialized keys rather than packed fixed-width keys. Add one focused external-aggregation regression that forces a serialized no-aggregate method and checks spilled output against the in-memory result.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: add the missing external-spill regression for the serialized _void_hash64 merge path.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.80% -0.10%
Functions 92.00% 91.90% -0.10%
Branches 79.20% 79.10% -0.10%

Changed lines: Changed C/C++ lines covered: 443/463 (95.68%) · Uncovered code

Full report · Diff report

@nickitat nickitat removed the ci-performance performance only label Jun 30, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
nickitat and others added 3 commits June 30, 2026 09:05
…v gate)

The `std::getenv("CH_NO_VOID")` A/B gate was prototype scaffolding. It tripped
`clang-tidy`'s `concurrency-mt-unsafe` check (`std::getenv` is not thread safe and
the `Aggregator` is constructed concurrently), failing the `arm_tidy` build.

Selecting the void-mapped hash table for `GROUP BY` of fixed-width keys without
aggregate functions is a purely internal data-structure choice: results are
identical to the regular path and it is never slower, so - like the existing
`key8`/`key16`/.../`keys256` method selection - it is now unconditional rather
than gated.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108862&sha=latest&name_0=PR
PR: #108862

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`Aggregator::mergeBlocks` upgrades `key64`/`keys128`/`keys256` to their
`*_hash64` variants before merging externally-aggregated data, because the
merged key count can exceed 4 billion and the `HashCRC32` tables (~32 bits of
entropy) would then collide badly. The void methods bypassed this: once
`method_chosen` was remapped to `key64_void`/`keys128_void`/`keys256_void`, the
`APPLY_FOR_VARIANTS_THAT_MAY_USE_BETTER_HASH_FUNCTION` list no longer matched, so
large external no-aggregate `GROUP BY` (effectively `DISTINCT`) merges fell back
to the weak hash - turning the intended speedup into a collision-driven
regression.

Add void-mapped `*_hash64` merge targets (`key64_void_hash64`,
`keys128_void_hash64`, `keys256_void_hash64`) that keep the key-only cell but use
the full-width `DefaultHash`/`UInt128Hash`/`UInt256Hash`, and remap the void
methods to them in `mergeBlocks`. This preserves both the memory win and the
better-hash invariant exactly where it matters most - huge external merges.
`key32_void`/`keys32_void`/`keys64_void` are intentionally not remapped, matching
the existing non-void `key32`/`keys32`/`keys64` which also keep `HashCRC32`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Interpreters/Aggregator.cpp Resolved
nickitat and others added 4 commits June 30, 2026 10:21
Adds void-mapped counterparts of the serialized aggregation methods
(`serialized`/`prealloc_serialized` and their nullable forms), selected for
`GROUP BY` without aggregate functions whose keys don't fit the fixed-width
methods - i.e. multiple columns, strings mixed with other types, or complex
types like `Array`/`Tuple`. This is the general fallback method, so it covers a
large class of `DISTINCT`-shaped queries.

The cells keep only the key and a saved hash (new `AggregatedDataVoidCellWithSavedHash`,
24 bytes instead of 32 for `string_view`), dropping the dead `AggregateDataPtr`.
The saved hash matters here because the keys are serialized blobs in an Arena and
recomputing their hash on every probe is expensive. Single-level, two-level and
`*_hash64` (external-merge) variants are added; the merge upgrade to the better
hash is wired up exactly like the existing `serialized` -> `serialized_hash64`.

Verified: method selection picks the `*_void` variants; full-result A/B against
`SELECT DISTINCT` matches (including forced external aggregation through the
`*_void_hash64` merge path).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Adds void-mapped counterparts of the nullable fixed-width methods
(`nullable_key32`/`nullable_key64` and `nullable_keys128`/`nullable_keys256`),
selected for `GROUP BY` without aggregate functions over a single nullable
number or several nullable fixed-width columns.

For the single-number variants the void map is wrapped in
`AggregationDataWithNullKey` just like the non-void one - the null group's
presence is still tracked by the one-bool/one-dead-pointer header (O(1)), only
the non-null keys live in the key-only cells. For the packed `keys128`/`keys256`
variants the null bitmap is part of the key, so the existing void maps are reused
with `has_nullable_keys = true`. These methods are not in the better-hash
external-merge list (matching their non-void counterparts), so no `*_hash64`
variants are needed.

Verified: method selection picks the `nullable_*_void` variants; full-result A/B
against `SELECT DISTINCT` matches with NULLs present, across single-level,
two-level and forced external aggregation.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`AggregatedDataVoidCellWithSavedHash`'s `(key, state)` constructor intentionally
leaves `saved_hash` uninitialized - it is set by `setHash` immediately after
placement construction on insert, and storing it twice on the hot aggregation
path is wasteful. This is exactly what `HashMapCellWithSavedHash` does; suppress
the `cppcoreguidelines-pro-type-member-init`/`hicpp-member-init` warning the same
way, which was failing the `arm_tidy` build.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108862&sha=latest&name_0=PR&name_1=Build+%28arm_tidy%29

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A `GROUP BY` without aggregate functions (effectively `DISTINCT`) has no per-key
state, so its "data" should be a set, not a map. The prototype faked this with a
custom key-only cell in a `HashMapTable` whose `getMapped` returned a
`thread_local` dummy - the wrong abstraction (a map without a mapped value is a
set, and those classes already exist).

Switch the void variants to the existing `HashSet` / `TwoLevelHashSet` /
`HashSetWithSavedHash` (and their better-hash external-merge counterparts),
exactly as `SetVariants` does for `DISTINCT`/`IN`. The set cells report
`VoidMapped`, and `AggregationMethod` now collapses that to `Mapped = void`
(`AggregationMethodMapped`, mirroring `SetMethodMapped`) so the shared
`ColumnsHashing` `HashMethod`s run in set mode (`has_mapped == false`). The same
`OneNumber`/`KeysFixed`/`Serialized` key methods, two-level conversion and
`*_hash64` merge upgrade are reused - only the container changes.

The Aggregator honors set mode with `if constexpr (has_mapped)` /
`std::is_void_v<Method::Mapped>` guards on the state-touching paths
(`executeImplBatch`, `mergeStreamsImplCase`, convert, `destroyImpl`, the
no-more-keys merges, inline-count); the void merge is the set's native `merge`.
`HashMap`/`HashMapTable` are left completely untouched. The custom void cells are
deleted. `LimitByTransform`/`NegativeLimitByTransform`, which reuse `chooseMethod`
and store a group index in the mapped slot, reject void methods as unreachable.

`HashSetTable`/`TwoLevelHashSetTable` lose `final` so `AggregationDataWithNullKey`
can wrap them for nullable set-mode keys (the map's `HashMapTable` is non-final for
the same reason), and gain a `forEachValue(func(key))` mirroring `HashMapTable`.

No behavior change: full-result A/B of void `GROUP BY` against `SELECT DISTINCT`
matches across fixed-width / serialized / nullable keys, single-level, two-level
and external aggregation; aggregate queries, `LIMIT BY` and `uniqExact`/`DISTINCT`
are unaffected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 8 query(s) improved out of 34 analysed

This PR reworks the aggregation hot path: it adds set-mode (void-mapped) hash tables for GROUP BY without aggregate functions and gates adaptive-aggregation producer creation behind its enable flag. Eight GROUP BY / aggregation queries improved consistently (clickbench Q13/Q15/Q16/Q18/Q30/Q33, plus tpch Q7 at x8.3 faster and Q8 at x2.1 faster), each with CPU dropping in step with wall time, so the deltas are work-backed rather than noise. clickbench Q23 was flagged x2.3 faster but is a SELECT * with filter, sort and LIMIT that runs no aggregation and sits on very noisy measurements, so it is downgraded to not-sure. The envelope-suppressed Q31 checks out: its CPU is essentially flat while wall time shifted and the median falls within master's own variance band.

clickbench

🟢 6 improved · ⚠️ 1 inconclusive

Flagged queries (7 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 13 improvement 422 339 -19.7% <0.0001 aggregation: GROUP BY with count(DISTINCT) runs on the aggregation path this PR reworks; the -19.7% drop is matched by a proportional CPU reduction, so it is real.
🟢 15 improvement 192 162 -15.9% <0.0001 aggregation: Plain GROUP BY count() on the reworked aggregation path; -15.9% with CPU falling in step and consistent across both tests.
🟢 16 improvement 734 614 -16.3% <0.0001 aggregation: Two-key GROUP BY count() on the aggregation path this PR restructures; -16.3% is work-backed by the matching CPU drop.
🟢 18 improvement 1244 1056 -15.1% <0.0001 aggregation: Three-key GROUP BY count() on the reworked aggregation path; -15.1% held up despite noisier measurements, with CPU dropping in step.
🟢 30 improvement 279 236 -15.4% <0.0001 aggregation: GROUP BY SearchEngineID/ClientIP on the reworked aggregation path; -15.4% tracks the CPU reduction.
🟢 33 improvement 1250 1155 -7.6% <0.0001 aggregation: GROUP BY URL count() on the reworked aggregation path; -7.6% is modest and matched by the CPU drop.
⚠️ 23 not_sure 164 72 ×2.3 faster <0.0001 SELECT * with filter, sort and LIMIT runs no aggregation, so this PR's hash-table and aggregation changes cannot touch it; the x2.3 faster reading sits on very noisy source measurements and reads as variance.

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

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 559 67 ×8.3 faster <0.0001 aggregation: Aggregation-heavy query on the path this PR restructures; x8.3 faster with CPU dropping proportionally, so the large delta is real and work-backed.
🟢 8 improvement 166 78 ×2.1 faster <0.0001 aggregation: Aggregation query on the reworked path; x2.1 faster confirmed by both tests and a matching CPU reduction.

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.

Debug info
  • StressHouse run: a9eb952a-ef71-40e8-8cef-0882d6eba192
  • MIRAI run: b563ca1e-97ee-4e22-92af-0f5836af6b42
  • PR check IDs:
    • clickbench_122811_1787147713
    • clickbench_122818_1787147714
    • clickbench_122828_1787147714
    • tpch_adapted_1_official_122841_1787147713
    • tpch_adapted_1_official_122868_1787147715
    • tpch_adapted_1_official_122882_1787147713

nickitat and others added 2 commits June 30, 2026 17:26
The `arm_tidy` build failed with `clang-analyzer-core.NonNullParamChecker`
on `state.emplaceKey(data, i, *arena_for_keys)` in the `Mapped == void`
(GROUP BY without aggregates) branch of `mergeStreamsImplCase`. The
analyzer cannot prove `arena_for_keys` is non-null, even though it is set
to `aggregates_pool` immediately above. The existing non-void branch
already suppresses the identical pattern with the same `NOLINT`, so apply
it to the void branch as well. No behavior change.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108862&sha=latest&name_0=PR&name_1=Build+%28arm_tidy%29
Related: #108862

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@nickitat nickitat changed the title Void-mapped hash table for GROUP BY without aggregates Use HashSet for group by-s without aggregates Jul 1, 2026
@nickitat nickitat changed the title Use HashSet for group by-s without aggregates Use HashSet for aggregations without aggregates Jul 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.60% -0.10%

Changed lines: Changed C/C++ lines covered: 293/308 (95.13%) · Uncovered code

Full report · Diff report

@nickitat

nickitat commented Aug 3, 2026

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

# Conflicts:
#	src/Interpreters/AggregatedData.h
#	src/Interpreters/AggregatedDataVariants.h
#	src/Interpreters/Aggregator.cpp

Copilot AI commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Resolved in d60f4c8. Three files had conflicts:

  • AggregatedData.h: kept our void type aliases and added master's AggregatedDataWithPackedStringKey
  • AggregatedDataVariants.h: kept our key32_void/key64_void fields and adopted master's AggregationMethodPackedString for key_string/key_string_two_level
  • Aggregator.cpp: kept our void-method switching block and added master's method_chosen_for_in_order logic (extended with prealloc_serialized_void → serialized_void and nullable_prealloc_serialized_void → nullable_serialized_void cases for the in-order path)

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ nickitat
❌ Copilot
You have signed the CLA already but the status is still pending? Let us recheck it.

…P BY

`mergeSingleLevelPartitionImpl`, added by the parallel single-level merge
(`enable_parallel_single_level_merge`), assumes every cell of an aggregation
method has an `AggregateDataPtr` mapped value. The set-mode methods of this
branch (`GROUP BY` without aggregate functions) report `VoidMapped` instead,
so the `Fast test` build failed to compile the merge for all 14 `*_void`
variants that `APPLY_FOR_VARIANTS_CONVERTIBLE_TO_TWO_LEVEL` dispatches:

    Aggregator.cpp:2205:9: error: no matching function for call to object of
    type '(lambda at Aggregator.cpp:2178:29)'
    note: candidate function not viable: no known conversion from 'VoidMapped'
    to 'AggregateDataPtr &' (aka 'char *&') for 2nd argument

Give the merge a void-mapped path, the same way `mergeDataImpl` and its
siblings already have one: a set cell carries no aggregate state, so merging
a source cell into the destination is a plain key union - nothing to adopt,
batch-merge or destroy - and for a single nullable key only the presence of
the NULL group travels from the source's dedicated slot to the destination's.
The non-void path is unchanged.

`GROUP BY` without aggregate functions had no stateless test over this merge,
so add one covering `key64_void`, `keys128_void`, `prealloc_serialized_void`,
`nullable_key64_void` and `nullable_keys256_void`, plus the matching unit
tests next to the existing per-method ones.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108862&sha=d60f4c88b87c432a9558b83487fdf4b79fac09de&name_0=PR&name_1=Fast+test
Related: #108862

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LJmHFQH2TPX9kHnwtWZe7f
nickitat added a commit that referenced this pull request Aug 6, 2026
The void/set-mode branches added for `GROUP BY` without aggregate functions wrap
sizeable stretches of the existing code in `if constexpr` guards. Those bodies
were left at their original indentation to keep the diff small, with a trailing
`/// end of ...` comment standing in for the missing indentation level. That
trades readability of the file for readability of one diff, so indent them
properly and drop the marker comments; `git diff -w` shows the change is
whitespace only, apart from the two points noted below.

The guards themselves have to stay. Only the discarded branch of an
`if constexpr` escapes instantiation - statements after it are still
instantiated for every type the enclosing template is used with - so replacing
a guard with a bare early `return` does not work. In
`estimateSizeOfCompressedState` it fails as:

    error: no member named 'forEachMapped' in 'HashSetTable<unsigned long,
    HashTableCell<unsigned long, DefaultHash<unsigned long>>>'

because `forEachMapped` exists only on the map tables. That function is now
written in early-return form with the guarded code in the `else`, and carries a
comment saying why the `else` cannot be dropped.

Also align the continuation backslashes of
`APPLY_FOR_VARIANTS_THAT_MAY_USE_BETTER_HASH_FUNCTION` to one column - the added
`*_void` entries are longer than the previous alignment allowed - and reduce the
two single-statement void branches to a plain `return;`, matching `destroyImpl`.

Related: #108862

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LJmHFQH2TPX9kHnwtWZe7f
The master merge brought the adaptive aggregator and the bucket-local Top-K
conversion. Both dispatch over every aggregation variant, the set methods of this
branch among them, and both are written against a cell's mapped value, so the
build failed on `AdaptiveAggregationKernels.cpp` and on `convertOneBucketToChunkTopK`.

Neither can apply to a set method. `bucket_top_k` ranks groups by a lone `count()`,
which an aggregation with no aggregate functions cannot have. The adaptive path
freezes a table of aggregate states and replicates the rest through per-bucket
backlogs; teaching its kernels to carry keys without states is a change of its own,
against a part of the codebase this branch has not touched. So constrain
`executeFrozenImpl`, `drainAdaptiveBucketImpl`, `drainAdaptiveBucketBacklog` and
`convertOneBucketToChunkTopK` on `MapAggregationMethod` and give each a set
overload that throws, as `LimitByTransform::consumeImpl` already does.

For that to be unreachable rather than merely unreached, `AggregatingTransform` now
skips creating the adaptive producer when the aggregator chose a set method.
Nothing is staged without a producer, so the merge-time drains find empty backlogs
and return at once. Note this is a real loss for `GROUP BY` without aggregates,
which on master does take the adaptive path - the two optimizations are exclusive
for now, and the set method wins by default. Extending the adaptive path to set
methods is worth doing separately.

`04654_adaptive_aggregator_profile_events` asserted the adaptive counters fire, and
stopped seeing them: each of its queries wrapped the aggregate in
`SELECT count() FROM (...)`, where the analyzer prunes it and leaves a `GROUP BY`
with no aggregates - a set method here. The outer queries now consume the inner
aggregate, which is what they meant to do.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108862&sha=5995c0993d7c44cbbfe5f2b9116487263c050be2&name_0=PR
Related: #108862

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LJmHFQH2TPX9kHnwtWZe7f
@nickitat

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

# Conflicts:
#	src/Interpreters/AggregatedDataVariants.h
#	src/Interpreters/Aggregator.cpp

Co-authored-by: nickitat <[email protected]>

Copilot AI commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Resolved in 67eff80. Two files had conflicts:

  • AggregatedDataVariants.h: kept our serialized_void_hash64/nullable_serialized_void_hash64/etc. fields and macro entries alongside master's new nullable_key64_hash64/nullable_keys128_hash64/nullable_keys256_hash64 additions
  • Aggregator.cpp: kept our serialized_void/nullable_serialized_void/etc. macro entries alongside master's new nullable_key64/nullable_keys128/nullable_keys256 entries

nickitat and others added 2 commits August 17, 2026 22:33
…ansform

Skipping the adaptive producer in `AggregatingTransform` was too late.
`initDataVariantsWithSizeHint` reads `params.enable_adaptive_aggregator` first, and
on a repeated query - `collect_hash_table_stats_during_aggregation` is on by
default - a size hint at or above the freeze threshold sends it down the
adaptive-only branch, which starts the table single-level and capped at twice that
threshold. That is right for a table about to freeze and wrong for a set method,
which cannot: it forfeits both the hint and the two-level initialization that the
other branch would have given it.

Clear the flag in the constructor instead, where the method is finally known.
`initDataVariantsWithSizeHint` then takes the ordinary branch, and the transform
gates on the aggregator's own copy through `getParams`, so there is one flag rather
than a flag and a second predicate beside it.

Measured on `SELECT number AS g FROM numbers_mt(2000000) GROUP BY g`, eight threads,
with the hint in place: the tables started `key64_void` and converted to two-level
eight times at run time; they now start `key64_void_two_level` and convert none,
matching what the same query does with the setting off. A map method with an
aggregate still freezes on all eight threads.

Related: #108862

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LJmHFQH2TPX9kHnwtWZe7f
The external-merge remap covers `key64_void`, `keys128_void` and `keys256_void`,
and since the nullable fixed-width map methods joined it, their set counterparts
were the only fixed-width methods left hashing spilled merges with `HashCRC32`.
`GROUP BY` without aggregate functions on a nullable `UInt64` or on packed nullable
keys is an ordinary workload that can pass 4 billion distinct keys, so it wants the
wider hash for the same reason the others do.

Add `nullable_key64_void_hash64`, `nullable_keys128_void_hash64` and
`nullable_keys256_void_hash64`, and remap to them. Only the single nullable key
needs a new data type, `AggregationDataWithNullKey` over the void hash64 table; the
packed forms reuse `AggregatedDataWithKeys128VoidHash64` / `...256...` with
`has_nullable_keys`, a nullable packed key carrying its null map inside the key.

The test mirrors 04836 on the set side. Its key widths are what select each method:
two `UInt32` keys fit the 128-bit packed form, two `UInt64` keys need the 256-bit
one. Checked from the trace that all three methods are the ones chosen and that the
queries really spill, rather than trusting the shape of the SQL.

Related: #108862

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LJmHFQH2TPX9kHnwtWZe7f
@@ -0,0 +1,35 @@
-- The set (void-mapped) counterpart of 04836. `GROUP BY` without aggregate functions on a nullable

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.

This new spill coverage still only exercises the nullable fixed-width _void_hash64 methods. The PR also adds serialized_void_hash64 / nullable_serialized_void_hash64, which is a separate correctness path because it relies on saved hashes and arena-backed serialized keys rather than packed fixed-width keys.

Please add one focused external-aggregation regression that forces those serialized _void_hash64 variants and checks equality against the in-memory result.

@nickitat
nickitat enabled auto-merge August 18, 2026 11:02
@nickitat
nickitat added this pull request to the merge queue Aug 18, 2026
@nickitat
nickitat removed this pull request from the merge queue due to a manual request Aug 18, 2026
nickitat and others added 2 commits August 18, 2026 16:02
The set methods were kept off the adaptive path: the aggregator cleared
`enable_adaptive_aggregator` once it picked one, and the three kernels the path needs
threw for them. That trades a large optimization for a smaller one wherever the two
meet - a multi-threaded `GROUP BY` without aggregate functions - and the performance
comparison shows the cost: `numbers_mt(10000000) GROUP BY number` regressed by 44%, the
same query with the two-level thresholds raised out of reach by 735%.

Nothing about the adaptive path needs a mapped value. A frozen local table answers
whether the key is already held, and a miss is staged as the key alone and emplaced
once by the merge-time drain; the mapped kernels carry places and aggregate states
through that only because they have states to advance. So implement the three kernels
for the set methods instead: `executeFrozenImpl` probes and stages the key with no
places array and no argument gathering, `drainAdaptiveBucketImpl` emplaces the staged
key and does nothing else, and `drainAdaptiveBucketBacklog` stays one function for both
kinds with the count-carrying lines guarded, since its routing, reserve sampling and
slicing do not depend on the payload.

The all-keys-are-const case stages a single record for the whole range: a set stores a
key once however many rows carry it, while the mapped kernel has to stage a record per
row because each row's aggregate arguments differ.

Measured against master on the same machine, interleaved, 9 runs each:

  numbers_mt(10000000) group by number     29 -> 22 ms, 529 -> 372 MiB
  numbers_mt(50000000) group by number    151 -> 94 ms, 1.77 -> 1.58 GiB
  numbers(10000000) group by number       417 -> 293 ms, 512 -> 256 MiB
  the same, two-level thresholds at 1e12   29 -> 22 ms, 509 -> 386 MiB

The regressed shapes are now faster than master rather than merely level with it, and
the void cell's memory win applies to the multi-threaded shapes as well.

https://s3.amazonaws.com/clickhouse-test-reports/PRs/108862/22519e1c6e7980aa669a5eaaae7ba37a05db02fb/performance_comparison_amd_release_master_head_5_6/report.html
#108862

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LJmHFQH2TPX9kHnwtWZe7f
@nickitat
nickitat force-pushed the void-mapped-groupby branch from 9a4ee4d to 338fac2 Compare August 18, 2026 19:02
@nickitat
nickitat added this pull request to the merge queue Aug 19, 2026
Merged via the queue into master with commit dddf61c Aug 19, 2026
345 of 346 checks passed
@nickitat
nickitat deleted the void-mapped-groupby branch August 19, 2026 18:21
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
thevar1able added a commit that referenced this pull request Aug 19, 2026
…y-limit-pushdown

Resolves the overlap with #108862 (HashSet for aggregations without
aggregate functions) by wiring the top-K heap into the new set path:
`executeImplBatchNoAggregates` gets the skip/push/trim logic, both
`executeImplBatch` overloads share one signature, the set-mode
`EmplaceResult` carries the key for the heap, and the prune path skips
the aggregate-state destruction that set methods do not have. Keys-only
`GROUP BY ... ORDER BY ... LIMIT` keeps the optimization on the set
path, including hash-table pruning.

Co-Authored-By: Claude Fable 5 <[email protected]>
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Aug 23, 2026
…cell is created

A `GROUP BY` with no aggregate functions keeps a hash table whose mapped value is a sentinel that
nothing ever reads. Keys that have a set counterpart hold no value at all, but a `String`,
`FixedString` or `LowCardinality` key still uses a mapped table, and there every row wrote the
sentinel again:

    state.emplaceKey(method.data, row, *aggregates_pool).setMapped(place);

`setMapped` writes both the cell and the keys cache, so a row whose key is already in the table paid a
store into a random place of the table for nothing. Do it only when the row created the cell; for
every other row the cell already holds the same sentinel.

Measured against a build of the parent commit, same checkout, through `perf.py`, 100M rows:

  GROUP BY a LowCardinality(String), 50k distinct   260 -> 241 ms   (p = 4e-6)
  GROUP BY a String, 1M distinct                    386 -> 373 ms   (p = 2e-4)

and -12% for the LowCardinality query at `max_threads = 32`. `SELECT DISTINCT` does not change: it
does not go through the aggregator.

Found while decomposing where ClickHouse#108862 gets its speedup
from - for the key types that PR covers, this store was most of it.

Related: ClickHouse#108862

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Aug 31, 2026
…ty as a mapped one

The aggregation loop turns its software prefetch on once the hash table outgrows L2, and it decides
that on the table's size **in bytes**. A `GROUP BY` without aggregate functions runs on a `HashSet`
whose cells carry no mapped value, so the same number of cells takes half the bytes - and the number
of cells, one random lookup each, is what decides how many of those lookups miss. The set methods
therefore started prefetching only at twice the cardinality of an equivalent mapped table, and lost
the prefetch exactly in the range where the table stops fitting and it is worth the most.

Halve the threshold for a method whose cells hold no mapped value; nothing changes for the others.

Measured against a build of the parent commit, same checkout, through `perf.py`, 200M rows over 131k
distinct keys:

  max_threads = 1     3093 -> 2823 ms   (p = 2e-7)
  max_threads = 8      392 ->  363 ms   (p = 7e-9)
  max_threads = 32     112 ->  103 ms   (p = 4e-3)

and, single-threaded on the same shape at other cardinalities, -6% at 60k keys, -1% at 200k, unchanged
at 3M (where both prefetch anyway). Results are identical - this only decides a prefetch hint - and the
mapped path, with or without aggregate functions, is untouched.

Found while decomposing where ClickHouse#108862 gets its speedup
from: this window was the one place where the set methods were barely faster than the mapped ones.

Related: ClickHouse#108862

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
awitten1 pushed a commit to awitten1/ClickHouse that referenced this pull request Oct 10, 2026
`test_memory_limit/test.py::test_multiple_queries` fills a 4 GB container
with 30 unbounded `SELECT * FROM system.numbers GROUP BY number` queries
(15 concurrent), so its run time is the number of rows needed to reach the
server limit times the per-row cost. On the coverage build the per-row cost
is very high: in the failing job of ClickHouse#123493 the first wave of 15 queries
needed 216 s to reach the 3.60 GiB limit, while the whole test takes about
50 s on a release build.

ClickHouse#108862 switched this query to a `HashSet` (8 bytes per key instead of 16),
so each query now inserts about twice as many rows before it is stopped.
On master coverage runs the test went from 240 s at 581c15c to 424 s
at the ClickHouse#108862 merge, and the weekly median is now about 570 s with a
maximum of 909 s, against the 900 s pytest timeout. It timed out 5 times
in 60 days, always on coverage shards.

Modules in `LLVM_COVERAGE_SKIP_PREFIXES` run in
`Integration tests (amd_binary_excluded_from_llvm)` instead, so the test
keeps running unchanged on a regular binary (and on arm_binary and
amd_cfi). The trailing slash keeps `test_memory_limit_observer/` in the
coverage shards.

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

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.

5 participants