Skip to content

Compute a single keyless uniqExact by radix partitioning - #123552

Merged
Algunenano merged 52 commits into
ClickHouse:masterfrom
Algunenano:radix-uniq-exact
Oct 20, 2026
Merged

Algunenano merged 52 commits into
ClickHouse:masterfrom
Algunenano:radix-uniq-exact

Conversation

@Algunenano

@Algunenano Algunenano commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Compute a single uniqExact (and count(DISTINCT), which uses it by default) of a query without GROUP BY by partitioning the values by their hash instead of merging per-thread hash sets. Every stream routes its values by the top bits of their hash into buckets, appending them to a buffer of its own per bucket; after all streams are finished, one set per bucket is built in parallel from the buffers of all the streams, small enough to stay in the CPU cache, and only its size is kept. The result is the sum of the sizes.

The ordinary aggregation builds a set per thread and merges them; once the sets outgrow the CPU caches, both the inserts and the merge are bound by cache misses, and the per-thread sets duplicate the keys that several threads see.

To avoid regressions on other shapes:

  • A stream starts with a small local set, so low-cardinality inputs behave as before. It switches to the routing only when the set would outgrow 1 MiB.
  • While routing, consecutive duplicates are skipped (runs of equal values, such as the sorted CounterID, one vector register at a time, and the empty string once per stream), and the buffered keys are deduplicated when they exceed a budget: a sample of the buffers is deduplicated first, and the decision is made on the keys routed since the last deduplication, so they stay within a small factor of the distinct keys of the stream.
  • If most keys turn out to be repeated and the distinct keys of the stream fit into 4 MiB, the stream goes back to an unbounded local set, as the ordinary aggregation does. Larger sets do not fit into the caches, and routing beats them even with the repeated deduplications.
  • The number of distinct keys, the per-stream numbers, and whether most streams ended in a local set are kept in the hash table statistics (RadixUniqExactEntry, keyed like the statistics of GROUP BY). A repeated run of the query uses them: enough buckets for each bucket set to fit into the L2 cache, bucket sets allocated for the expected number of keys, and streams starting in the mode the first run ended in. The mode comes from the first run rather than from the size of the set: keys that repeat soon after they are seen (the timestamps of hits) are faster in a local set even above 4 MiB, while keys that repeat as often but at random are faster routed. A stream whose keys are at most twice its budget is not deduplicated, as a deduplication late in the stream only repeats the build.
  • It is also used with max_threads = 1: there is no merge to avoid there, but the bucket sets stay in the cache while one big set does not.

It applies to a single-argument uniqExact without GROUP BY that is finalized on the same server, for numeric types up to 64 bits, Date, Date32, DateTime, Enum, IPv4, IPv6, UUID, 128-bit integers, String, FixedString and Nullable of them. Sparse columns route only their values. The keys are the same as in uniqExact: the bits of the value for numeric types, and the 128-bit SipHash for String, FixedString and IPv6 (through the new sipHash128Padded, which reads the last partial word of a padded column with one load and is 1.0x to 1.2x faster than SipHash::update). The slot in the sets is selected by Fibonacci hashing. Controlled by the new setting optimize_uniq_exact_radix_partitioning (enabled by default, randomized in clickhouse-test).

ClickBench hits (100M rows, ZSTD(3), one part) on an AMD Ryzen 9 7950X3D (Zen 4), the server pinned to 8 cores (16 threads) like the CI performance tests, medians of 7 hot runs (repeated runs, which use the statistics). "Off" is the ordinary aggregation (optimize_uniq_exact_radix_partitioning = 0), which is what master runs.

Query, 16 threads off on peak memory
count(DISTINCT UserID) (Q4) 0.135 s 0.049 s 2.8x 1.01 GiB → 285 MiB
count(DISTINCT SearchPhrase) (Q5) 0.249 s 0.143 s 1.7x 625 MiB → 447 MiB
count(DISTINCT WatchID) 0.651 s 0.106 s 6.1x 3.95 GiB → 1.02 GiB
count(DISTINCT URL) 1.458 s 0.798 s 1.8x 2.08 GiB → 1.94 GiB
count(DISTINCT ClientIP) 0.088 s 0.041 s 2.1x 385 MiB → 152 MiB
count(DISTINCT EventTime) 0.086 s 0.074 s 1.2x 291 MiB → 174 MiB
count(DISTINCT CounterID) 0.007 s 0.005 s 1.4x 5.6 MiB → 786 KiB
Query, 1 thread off on peak memory
count(DISTINCT UserID) 1.461 s 0.463 s 3.2x 1.00 GiB → 257 MiB
count(DISTINCT SearchPhrase) 2.203 s 1.293 s 1.7x 512 MiB → 258 MiB
count(DISTINCT WatchID) 5.630 s 0.828 s 6.8x 4.00 GiB → 897 MiB
count(DISTINCT EventTime) 0.417 s 0.416 s 1.0x 32 MiB → 24 MiB
count(DISTINCT CounterID) 0.047 s 0.032 s 1.5x 659 KiB → 212 KiB

On the whole machine (32 threads, earlier version of this PR, master → PR): Q4 0.163 s → 0.026 s, Q5 0.163 s → 0.068 s. On a 48-core Graviton4 (earlier version, 10 hot runs): Q4 0.050 s → 0.016 s, Q5 0.072 s → 0.050 s, WatchID 0.264 s → 0.037 s.

Known gaps: repeat-heavy medium-cardinality inputs (uniqExact(a) over number % 250000 or % 500000 of 50M rows) are up to 15% slower than master on the first run and use up to 3x its memory, because the routed keys are buffered until they are deduplicated. With the columns cache enabled (use_columns_cache = 1), Q5 is 0.062 s on 32 threads (master 0.163 s). Only measured on x86 in this form. Two alternatives for the string keys were measured and rejected: a random-key polynomial hash (GHASH-like, 1.1x to 1.2x faster on URL and Title, but a weaker kind of guarantee than SipHash once the key is known), and storing the strings with byte comparison (exact, but 1.4x to 2x slower and 3x to 8x the memory).

Related: #123531
Related: #124405

Changelog category (leave one):

  • Performance Improvement

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

count(DISTINCT x) and uniqExact(x) without GROUP BY are faster and use less memory for high-cardinality columns: the values are partitioned by hash and each partition is deduplicated in parallel in a cache-resident hash set, instead of merging per-thread hash sets, and repeated runs of a query reuse the statistics of the first one. 2.8x faster on ClickBench Q4 and 1.7x on Q5 with 16 threads, up to 6x on high-cardinality columns, with 2x to 4x less memory. Controlled by the new setting optimize_uniq_exact_radix_partitioning.


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

Version info

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

Algunenano and others added 5 commits October 2, 2026 13:28
A query like `SELECT count(DISTINCT UserID) FROM hits` builds a hash set per thread and then
merges them. Once the sets outgrow the CPU caches, both the inserts and the merge are bound by
cache misses. Instead, every stream now routes its keys by the top bits of their hash into
partitions, and after all streams are finished, one set per partition is built in parallel, small
enough to stay cache-resident, and only its size is kept. The result is the sum of the sizes.

A stream starts with a small local set, so low-cardinality inputs are not affected. While routing,
it skips consecutive duplicates, and it deduplicates its buffered keys when they accumulate
(sampling a few partitions first to decide whether it is worth it), so the buffered keys are
bounded by the distinct keys of the stream. If most keys turn out to be repeated, the stream goes
back to an unbounded local set, as the ordinary aggregation does.

Applies to a single-argument `uniqExact` (including `count(DISTINCT)`) without `GROUP BY` that is
finalized locally, for numeric types up to 64 bits, `Date`, `Date32`, `DateTime`, `Enum`, `IPv4`,
`IPv6`, `UUID`, 128-bit integers, `String`, `FixedString` and `Nullable` of them. It uses the same
keys as `uniqExact` (the value bits, or `SipHash128` for strings), so the results are identical.
Controlled by the new setting `optimize_uniq_exact_radix_partitioning` (enabled by default).

On a 48-core Graviton4 (`hits`, 100M rows, hot runs) compared to master:
- `count(DISTINCT UserID)`: 0.050 s -> 0.016 s, peak memory 1.0 GiB -> 334 MiB
- `count(DISTINCT SearchPhrase)`: 0.072 s -> 0.050 s, 1.4 GiB -> 672 MiB
- `count(DISTINCT WatchID)`: 0.264 s -> 0.037 s, 5.2 GiB -> 1.4 GiB

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Both values are picked with equal probability, so that the ordinary keyless `uniqExact`
aggregation, which the setting replaces by default, keeps being tested as well. The checks of
the pipeline in the test of the setting now enable it explicitly.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…`uniqExact`

The setting does not add `OrNull` to `uniqExact`, because it returns 0 for an empty set, so the
radix partitioned aggregation still applies. Check that it returns the same values and types as
the ordinary aggregation with the setting, for an empty and a non-empty input.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The partition is selected by the top bits of the finalizer of MurmurHash3, because they depend
on every bit of the key, so sequential keys are spread over the partitions, and the slot in a set by
CRC32, which is independent of it and cheaper. Use the existing `intHash64` instead of a copy of
the finalizer.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…hat do not fit into L2

When the set of a partition, or the unbounded local set of a stream, is larger than the L2
cache, prefetch the cell of the key 32 positions ahead while inserting, so that the cache misses
overlap. Smaller sets are left as is: they are cache-resident and the prefetch only costs there.

On a 48-core Graviton4 this matters only when the partitions are large, i.e. many distinct keys
and few threads: `count(DISTINCT WatchID) FROM hits` with 4 threads 0.267 s -> 0.246 s,
`uniqExact(number) FROM numbers_mt(1e8)` with 8 threads 0.144 s -> 0.124 s. Other queries are
unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Algunenano Algunenano self-assigned this Oct 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f61fd3d]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
Check Results FAIL IGNORED
Performance Comparison (amd_release, master_head, 6/6) FAIL Performance dashboard
join_used_flags #1 unstable query history IGNORED
polymorphic_parts_m #1 unstable query history IGNORED
polymorphic_parts_m #2 unstable query history IGNORED
qbit_l2_distance_float64_memory #0 slower query history IGNORED
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
Check Results FAIL IGNORED
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
polymorphic_parts_m #2 unstable query history IGNORED

AI Review

Summary

This PR computes a single locally finalized uniqExact or count(DISTINCT) without GROUP BY through radix partitioning, with cached statistics guiding subsequent executions. The performance gains are supported by measurements, but the current head (f61fd3d6754452826328a3f540c4e3f0833ab923) still reproduces two previously reported regressions, and the new execution strategy remains enabled by default without an experimental gate. ❌ Block. No genuinely new inline findings were identified; the dismissed findings below remain summary-only.

Findings

❌ Blockers

  • Buffered memory is not bounded by distinct keys for skewed inputs. RadixUniqExactTransform.cpp:831–834 [dismissed by author -- https://github.com/Compute a single keyless uniqExact by radix partitioning #123552#discussion_r4275153371]. The median sampled bucket can remain mostly unique while a few hot buckets accumulate repeated keys; this branch keeps increasing the budget without compacting those buckets. This remains real because the current CI binary still fails the following query with MEMORY_LIMIT_EXCEEDED at 130.01 MiB projected usage, while disabling the optimization returns 150001 under the same limit:

    SELECT uniqExact(if(number % 100 = 0, number, number % 2))
    FROM numbers(15000000)
    SETTINGS max_threads = 1, count_distinct_optimization = 0,
        collect_hash_table_stats_during_aggregation = 0,
        max_memory_usage = 100000000,
        optimize_uniq_exact_radix_partitioning = 1;

    Account for hot-bucket occupancy when deciding compaction and budget growth; add this focused regression.

  • Structured numeric keys still cause quadratic probing. RadixUniqExactTransform.cpp:85 [dismissed by author -- https://github.com/Compute a single keyless uniqExact by radix partitioning #123552#discussion_r4275153383]. Multiplying by the modular inverse of the slot-hash multiplier makes slotHash(x) equal number, so its high bits select slot zero throughout the local-set build. This remains a reproducible default-path regression even though the author considers the input adversarial: the current binary takes 2.4234 s enabled versus 0.0821 s disabled for only 60,000 rows:

    SELECT uniqExact(number * 17428512612931826493)
    FROM numbers(60000)
    SETTINGS max_threads = 1, count_distinct_optimization = 0,
        collect_hash_table_stats_during_aggregation = 0,
        optimize_uniq_exact_radix_partitioning = 1;

    Use an independent avalanche mix or bound probe-chain growth, and cover structured numeric inputs in the performance test. The same slot selection is used during bucket building and compaction.

  • The new execution strategy has no experimental opt-in. Settings.cpp:7456–7459 [dismissed by author -- https://github.com/Compute a single keyless uniqExact by radix partitioning #123552#discussion_r4275153398]. optimize_uniq_exact_radix_partitioning is default-enabled with flags 0, immediately changing existing queries. The reproduced memory-limit failure and quadratic probing still make an ungated initial rollout unsafe. Default it to disabled, mark it EXPERIMENTAL, and update its compatibility-history entry before promotion.

Missing context / blind spots
  • ⚠️ Runtime verification used the current head's fast-test binary. The full sanitizer, functional, and performance CI runs were still pending when reviewed; their completed reports are needed to assess the remaining platform and concurrency coverage.
Final Verdict

❌ Block. Bound buffering under skew, prevent quadratic numeric probing, add focused regression coverage, and introduce the execution strategy behind an experimental opt-in. The author's dismissals are preserved; no dismissed thread was reopened or re-commented.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Oct 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes, compile time of recompiled translation units.

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

153 object files changed (+425.91 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/RadixUniqExactTransform.cpp.o new 321.99 KiB +321.99 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashTablesStatistics.cpp.o 265.84 KiB 334.77 KiB +68.93 KiB (+25.93%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/AggregatingStep.cpp.o 596.37 KiB 627.53 KiB +31.16 KiB (+5.22%)

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

2587 translation units recompiled, 15424 s compile time in total, 790 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Functions/FunctionsNumericIndexedVector.cpp: 56.0 s
  • src/Functions/FunctionsConversion.cpp: 54.6 s
  • src/Formats/FormatFactory.cpp: 46.4 s
  • src/Functions/modulo.cpp: 41.1 s
  • src/Functions/array/arrayElement.cpp: 37.8 s
  • src/Dictionaries/SparseHashedDictionary.cpp: 35.4 s
  • src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp: 34.4 s
  • src/AggregateFunctions/AggregateFunctionUniq.cpp: 32.2 s
  • src/Functions/polygonsSymDifference.cpp: 30.9 s
  • src/Dictionaries/HashedDictionary.cpp: 29.2 s
  • src/Functions/intDiv.cpp: 27.8 s
  • src/Functions/array/mapPopulateSeries.cpp: 27.2 s
  • src/Functions/if.cpp: 26.9 s
  • src/Functions/FunctionsConversion_reg.cpp: 26.8 s
  • src/Functions/divide.cpp: 24.7 s
  • src/Functions/plus.cpp: 24.0 s
  • src/Functions/polygonsUnion.cpp: 23.8 s
  • src/AggregateFunctions/AggregateFunctionAvgWeighted.cpp: 23.6 s
  • src/Functions/polygonsIntersection.cpp: 23.6 s
  • src/Functions/minus.cpp: 23.2 s
  • ... and 429 more

Job report

Algunenano and others added 13 commits October 6, 2026 22:54
…re the build

`buildPartition` reads only the chains, so once a stream is finished, its local set is dead memory:
the unbounded set of a stream that went back to it has just been moved into the chains, and a
stream in the radix mode keeps the scratch set of its deduplications. The set stayed allocated
while the partition sets were built, so repeat-heavy inputs held both at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test ran for more than 180 seconds in the flaky check with sanitizers, mostly to compute every
value a second time with the ordinary aggregation, from a table of 2 million rows with 19 columns,
and in a few queries over 10 and 20 million rows. Check the values against the reference instead,
read the inputs from `numbers_mt` with 2 threads, and make them just large enough for the threads to
route their values (more than 32 thousand distinct 128-bit keys, 64 thousand 64-bit keys or 128
thousand 32-bit keys per thread).

Disable `optimize_injective_functions_inside_uniq` and `optimize_rewrite_aggregate_function_with_if`
in the test: they turned `uniqExact(toString(x))` into `uniqExact(x)` and `uniqExact(if(c, NULL, x))`
into `uniqExactIf`, so the strings and `Nullable` values did not reach the radix partitioned
aggregation. Use `toUInt64` for the repeated 64-bit values, because the result of `%` has the type of
the divisor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Exact` hash strings

`optimize_injective_functions_inside_uniq` rewrote `uniqExact(toString(number))` into
`uniqExact(number)`, so the query measured 64-bit keys instead of strings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…qExact`

`convertToFullIfWrapped` expanded a sparse column into a full one, so every default value was
compared, and with strings, materialized. The values column of a sparse column already holds the
default value once, followed by the other values. Route it as is if the column has default rows,
and without its first value otherwise.

`uniqExact(MobilePhoneModel)` over ClickBench `hits` (a sparse `String` column), 8 cores and
16 threads: 0.046 s -> 0.009 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ibonacci hashing

The low bits of CRC32 are a linear function of the bits of the key, so for some sizes of the set
they map pairs of the keys of a dense range to the same cell, and the inserts probe more cells.
Fibonacci hashing (Knuth, TAOCP vol. 3, 6.4), the top bits of the key multiplied by 2^64 divided by
the golden ratio, spreads such ranges almost without collisions, whatever the size of the set. The
128-bit keys use their high half, because their low half selects the partition.

8 cores, 16 threads: `uniqExact(toUInt64(intHash64(number) % 15000))` over 50 million rows
0.043 s -> 0.020 s, with `% 60000` 0.047 s -> 0.024 s. `count(DISTINCT EventTime)` over ClickBench
`hits` is 4% slower (0.159 s -> 0.165 s): CRC32 kept runs of nearby timestamps in a few cache
lines. The other ClickBench queries are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…act`

The keys were inserted one by one, and every store into a cell made the compiler reload the
fields of the set and the mode of the stream, because they could alias the cells. Insert the
batch of keys of a column, and the blocks of the chains in the deduplication and in the build,
with a loop that keeps the fields in local variables, when the set has room for all of them.

8 cores, 16 threads: `uniqExact(toUInt64(number % 10000))` over 50 million rows 0.017 s ->
0.011 s, `uniqExact(toUInt64(intHash64(number) % 60000))` 0.023 s -> 0.017 s,
`count(DISTINCT UserID)` over ClickBench `hits` 0.062 s -> 0.057 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tly routed keys

A stream went back to its local set when at most a quarter of its sampled buffered keys were
distinct. Once every key of a stream has been seen, a deduplication leaves the distinct keys and
the budget lets the stream buffer three times as many again, so the ratio is exactly a quarter
at every deduplication, whatever the number of repeats: whether the stream went back depended on
the noise of the sample. Most streams of repeat-heavy queries stayed in the radix mode and were
deduplicated again and again, which made `count(DISTINCT EventTime)` over ClickBench `hits`
slower than without the optimization.

- Decide by the keys that were routed since the last deduplication: the chains remember how many
  of their keys are known to be distinct.
- Go back to the local set only if it would not be larger than 4 MiB. Larger sets do not fit into
  the CPU caches, and inserting into them is slower than routing and deduplicating the keys in
  cache-resident sets.
- After a deduplication, let the stream buffer 8 times as many keys as remain, instead of 4, so
  that the repeated keys are deduplicated less often. The first deduplication after the switch
  to the routing keeps the factor of 4, because it decides whether the stream goes back, and the
  keys routed until then are wasted if it does.

8 cores, 16 threads: `count(DISTINCT EventTime)` 0.155 s -> 0.120 s,
`uniqExact(a)` over `number % 500000` of 50 million rows 0.114 s -> 0.104 s, over
`number % 100000` 0.066 s -> 0.063 s, `uniqExact(toUInt64(number % 500000))` over `numbers_mt`
0.083 s -> 0.079 s. With `number % 250000` and `% 1000000`, and `count(DISTINCT UserID)`, the
differences are within the noise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The keys of the values (numbers and other fixed-size types) skip the consecutive duplicates by
  comparing each row with the previous row of the column, so that the only dependency between the
  iterations is the number of keys. As in the ordinary `uniqExact`, the duplicates are looked for
  only while they are frequent.
- The keys of strings are computed into the same buffer as the keys of the values, and the
  strings are compared through the offsets of the column.
- The batch is inserted into the local set, or pushed into the chains, checking the mode and the
  budget of the deduplication once for as many keys as possible.

8 cores, 16 threads, ClickBench `hits`: `count(DISTINCT SearchPhrase)` 0.220 s -> 0.193 s,
`count(DISTINCT EventTime)` 0.123 s -> 0.116 s; 32 threads: `count(DISTINCT SearchPhrase)`
0.099 s -> 0.091 s. `UserID`, `ClientIP` and `WatchID` are within the noise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ians over the sample

The sample of a deduplication covered as many chains as needed for 4096 keys, often two or three,
and the decisions used the totals of the sample. A key that is repeated much more often than the
others, such as an empty string, is in a single chain, so a sample that contained that chain made
all the keys of the stream look repeated. Sample at least 8 chains, and decide by the medians of
the ratios of the chains.

8 cores, 16 threads: `uniqExact(toUInt64(number % 500000))` over 50 million rows 0.075 s ->
0.068 s, `uniqExact(a)` over `number % 500000` 0.102 s -> 0.098 s. `count(DISTINCT SearchPhrase)`
and `count(DISTINCT EventTime)` over ClickBench `hits` are within the noise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d `uniqExact`

`SipHash::update` reads the last partial word of the data through a jump on its length to a load
of every byte, which is mispredicted when the lengths of the strings vary. `sipHash128Padded`
returns the same hash as `sipHash128` for data that is followed by at least 7 readable bytes, such
as a value of a padded column: it reads the last partial word with one load and a mask, and keeps
the state in local variables. The test checks that it equals `sipHash128` for every length up to
300 and every alignment.

For 1 million strings of random lengths from 1 to 60 bytes, 17.7 ns -> 14.5 ns per string on one
core; for strings of 8 bytes and longer the difference is within 4%. 8 cores, 16 threads, ClickBench
`hits`: `count(DISTINCT SearchPhrase)` 0.196 s -> 0.180 s (the medians of 6 runs, which vary by up to
15% between the restarts of the server), `count(DISTINCT URL)` and `count(DISTINCT Title)` 3% faster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ey polynomial hash

The keys of the radix partitioned `uniqExact` never leave the query, so they do not have to equal
the keys of the ordinary `uniqExact`, and their hash can have a random key, chosen for each query.
`UniversalHash128` is a polynomial hash over GF(2^128), as GHASH in AES-GCM: the value at the key
of the polynomial whose coefficients are the 16-byte blocks of the string, and whose constant term
is its length. For two different strings of at most n blocks, the probability over the key that
their hashes are equal is at most n / 2^128, whatever the strings, as long as they are chosen
without knowing the key; `SipHash` with its fixed key relies on its collisions being hard to find.

The blocks are multiplied by the precomputed powers of the key independently with carry-less
multiplication (PCLMULQDQ, PMULL on ARM), by Karatsuba's method, and reduced once for up to 8
blocks. Without carry-less multiplication, it is `sipHash128Padded`. The hash is linear over GF(2)
in the bits of the string, so it is mixed by the same bijection as the other 128-bit keys before
its bits select the partition and the slot. The test compares it with a bit-by-bit implementation
for every length up to 400.

One core, 1 million strings: 56 bytes 19.6 ns -> 7.4 ns per string, random lengths from 1 to 60
bytes 14.5 ns -> 9.0 ns. ClickBench `hits`, 8 cores and 16 threads: `count(DISTINCT URL)`
0.93 s -> 0.78 s, `count(DISTINCT Title)` 0.86 s -> 0.69 s, `count(DISTINCT SearchPhrase)`
0.187 s -> 0.182 s (the medians of 3 runs, which vary by up to 15% between the restarts of the
server); 32 threads: 0.399 s -> 0.362 s, 0.391 s -> 0.325 s and 0.092 s -> 0.080 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep the number of distinct keys, and the medians over the streams of the numbers of keys and of
distinct keys of a stream, in the statistics of hash tables after a query (`RadixUniqExactEntry`,
keyed by the plan as the statistics of the ordinary aggregation). When the same query runs again
with as many streams, use them instead of the estimates of the first run:

- Select enough partitions for each partition set to fit into half of the L2 cache.
- Allocate the partition sets for the expected number of their keys instead of the number of the
  buffered keys, which may be many times larger.
- Start a stream in a local set allocated for all its keys if the set is at most 4 MiB, as the
  first run would end, and in the radix mode otherwise, without deduplications if its keys were
  mostly distinct.

The keys of the statistics were computed only for the aggregations with keys, because the method
without keys does not use them; now they are also computed for a single `uniqExact` without keys,
and the ordinary aggregation without keys still does not collect or use them.

ClickBench `hits`, the second and later runs, 8 cores and 16 threads: `count(DISTINCT WatchID)`
0.307 s -> 0.161 s, `count(DISTINCT SearchPhrase)` 0.187 s -> 0.138 s, `count(DISTINCT UserID)`
0.058 s -> 0.056 s; 32 threads: `count(DISTINCT SearchPhrase)` 0.079 s -> 0.069 s,
`count(DISTINCT UserID)` 0.029 s -> 0.027 s. The other shapes and the runs without the statistics
are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Exact`

The empty string is often the most frequent value of a `String` column, and when it alternates
with other values, it is not a consecutive duplicate, so it was hashed and routed again at every
change: 7 of the 19 million keys routed by `count(DISTINCT SearchPhrase)` over ClickBench `hits`.
A stream now remembers that it has routed the empty string and skips it since then. The build
deduplicates the keys of the streams anyway.

ClickBench `hits`, `count(DISTINCT SearchPhrase)`: 8 cores and 16 threads 0.172 s -> 0.158 s,
32 threads 0.085 s -> 0.075 s. `URL`, `Title` and `UserID` are within the noise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Initialize the arrays of the powers of the key (`cppcoreguidelines-pro-type-member-init`), and allow
the constant seed of the random generator of the test, whose data must be reproducible
(`bugprone-random-generator-seed`).

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

@nihalzp nihalzp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The general idea looks good and it gives amazing speedup! The algorithm pipeline seems to be adaptive aggregator brought to life for global aggregation.

We should add some ProfileEvents so that we can inspect the algorithm's decisions under different workloads.

I have left some comments. They are not blocking but worth doing; it's okay if it's done in a separate PR.

@Algunenano

Copy link
Copy Markdown
Member Author

We should add some ProfileEvents so that we can inspect the algorithm's decisions under different workloads.

I'd rather refrain from adding ProfileEvents unless we really need to. We have so many and each one adds load both to system tables and in memory for all queries (the large array that has them all), so I'll add it in a followup if we need it at some point in the future.

Algunenano and others added 6 commits October 19, 2026 20:09
The argument type and the result type were checked only when the pipeline was built, in
`tryBuildRadixUniqExact`, which could still fall back to the ordinary aggregation. Now
`canUseRadixUniqExact` checks them too, through `isRadixUniqExactSupported`, so
`buildRadixUniqExact` always applies and `createRadixUniqExactState` throws on an unsupported
type. The plan optimization that stamps the statistics key uses the same decision, so it no
longer stamps a key for an argument type the radix path cannot compute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The hand-written open addressing set is replaced by a thin wrapper, `RadixSet`, around
`HashSetTable` with the same layout: cells of bare keys, linear probing, the load factor of 0.5,
and the slot selected by the top bits of `slotHash` through a custom grower. The grower never
grows the table by itself, the sets are still rebuilt by `growLocalSet`. The batch insert moves to
`HashSetTable::insertManyWithoutResize`, so it can serve the other sets too.

The performance is the same within noise, on 32 threads and on one thread, with and without the
statistics of hash tables. For example, `uniqExact(number)` over `numbers_mt(100000000)` with
`max_threads = 1` takes 690 ms with either set on a Ryzen 9 7950X3D.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The buffers of a stream hold tens of MiB, so the default arena, which doubles its chunks up to
128 MiB, always has its last chunk partly unused: the arenas allocated 1.4x to 2.9x the bytes of
the buffered keys. Past 1 MiB they now grow by 1 MiB, so the unused part is at most one chunk per
stream.

First runs of `count(DISTINCT ...)` over ClickBench `hits` (100M rows, 16 threads) on a Ryzen 9
7950X3D, memory before -> after, the time is the same within 2%:
- `WatchID`: 1200 MiB -> 922 MiB
- `UserID`: 257 MiB -> 202 MiB

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n when they are built

The builders fill their bucket sets at the same time, and when the sets are large they do not fit
into the caches together. Without statistics there are only 16 buckets per stream, so a column
with very many distinct values gets large bucket sets: `WatchID` from ClickBench (100M distinct
values) has 8 MiB sets with 256 buckets.

A bucket whose set would be larger than 2 MiB is now partitioned again by the next bits of its
hash, and a small set is built for each part, as the multi-pass radix partitioning of Boncz,
Manegold, Kersten, "Database Architecture Optimized for the New Bottleneck: Memory Access"
(VLDB 1999). It does not depend on an estimate of the number of distinct values, so it also
applies to filtered queries.

First runs of `count(DISTINCT WatchID)` over ClickBench `hits`:
- 8 threads: 229 ms -> 166 ms
- 16 threads: 126 ms -> 110 ms

`UserID`, `URLHash` and `SearchPhrase`, and the runs with statistics, are the same within noise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…m its buffers

Routing a key read and wrote the buffer (24 bytes), the header of its head block, and the key's
slot. The position and the end of the head block are now kept in a separate array of 16-byte
cursors, so routing a key only touches its cursor and its slot, and more cursors fit into the
cache. The sizes of the buffers and of their head blocks are brought up to date from the cursors
when a block is added and before they are read.

`count(DISTINCT ...)` over ClickBench `hits` with 8 to 32 threads is 1.04x faster on average
(up to 1.10x for `URLHash`), both on first runs and with the statistics of hash tables;
`SearchPhrase`, whose time goes to hashing the strings, is the same.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…q-exact

# Conflicts:
#	src/Processors/QueryPlan/BuildQueryPipelineSettings.cpp
@Algunenano

Copy link
Copy Markdown
Member Author

🤖 Follow-up on the review, pushed in f4bde203136:

  • The decision to use the radix path is made fully in canUseRadixUniqExact. createRadixUniqExactState throws LOGICAL_ERROR if the two disagree.
  • The bucket sets are a thin wrapper around HashSetTable with a custom grower and a new insertManyWithoutResize. Performance is the same as the old FlatSet, and the inner loop's assembly is the same.
  • The arenas of the buffers grow linearly past 1 MiB. The doubling arenas allocated 1.4x to 2.9x the bytes of the buffered keys. First-run memory of count(DISTINCT WatchID) went from 1200 MiB to 922 MiB, and UserID from 257 MiB to 202 MiB.
  • Large buckets are partitioned again when they are built, as in the radix-cluster algorithm (Boncz, Manegold, Kersten, VLDB 1999). Without statistics, a column with very many distinct values got bucket sets that don't fit into the caches together. First runs of count(DISTINCT WatchID) are 1.38x faster at 8 threads and 1.14x at 16. Nothing else changes.
  • The write cursors are kept apart from the buffers, so routing a key only touches its cursor and its slot. That's 1.04x faster on average and up to 1.10x for URLHash, both on first runs and with statistics.

Measured and not kept:

  • An online estimate of repeats. On ClickBench the decisions it would make match what the current checks already do; the remaining gaps between first runs and runs with statistics came from the bucket count and the deduplication threshold.
  • Choosing the bucket count from an online estimate. The total row count is counted before WHERE, so it can't be trusted; splitting large buckets during the build covers the same case.
  • Capping blocks at 256 keys. It saves about 10% of memory but costs 3–5% of time.

Spilling could reuse the per-partition spill streams of #123531 once both PRs are in.

@Algunenano

Copy link
Copy Markdown
Member Author

The performance failures are due to adding the setting to some tests. This is intended since those tests were testing somethign else and using radix enabled uniqExact would prevent that thing from being tested.

Other than that, no regressions (except if you look for adversarial examples, which we do not care about) and improvemetns of up to 97%

image

@alexey-milovidov

Copy link
Copy Markdown
Member

I'm disabling this setting by default: #127675

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.

4 participants