Repository navigation
Compute a single keyless uniqExact by radix partitioning - #123552
Conversation
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]>
|
Workflow [PR], commit [f61fd3d] Summary: ❌
AI ReviewSummaryThis PR computes a single locally finalized Findings❌ Blockers
Missing context / blind spots
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. |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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 ssrc/Functions/FunctionsConversion.cpp: 54.6 ssrc/Formats/FormatFactory.cpp: 46.4 ssrc/Functions/modulo.cpp: 41.1 ssrc/Functions/array/arrayElement.cpp: 37.8 ssrc/Dictionaries/SparseHashedDictionary.cpp: 35.4 ssrc/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp: 34.4 ssrc/AggregateFunctions/AggregateFunctionUniq.cpp: 32.2 ssrc/Functions/polygonsSymDifference.cpp: 30.9 ssrc/Dictionaries/HashedDictionary.cpp: 29.2 ssrc/Functions/intDiv.cpp: 27.8 ssrc/Functions/array/mapPopulateSeries.cpp: 27.2 ssrc/Functions/if.cpp: 26.9 ssrc/Functions/FunctionsConversion_reg.cpp: 26.8 ssrc/Functions/divide.cpp: 24.7 ssrc/Functions/plus.cpp: 24.0 ssrc/Functions/polygonsUnion.cpp: 23.8 ssrc/AggregateFunctions/AggregateFunctionAvgWeighted.cpp: 23.6 ssrc/Functions/polygonsIntersection.cpp: 23.6 ssrc/Functions/minus.cpp: 23.2 s- ... and 429 more
…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
left a comment
There was a problem hiding this comment.
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.
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. |
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
|
🤖 Follow-up on the review, pushed in
Measured and not kept:
Spilling could reuse the per-partition spill streams of #123531 once both PRs are in. |
…hanges Co-Authored-By: Claude Opus 5.5 <[email protected]>
c7531f5
|
I'm disabling this setting by default: #127675 |

Compute a single
uniqExact(andcount(DISTINCT), which uses it by default) of a query withoutGROUP BYby 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:
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.RadixUniqExactEntry, keyed like the statistics ofGROUP 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 ofhits) 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.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
uniqExactwithoutGROUP BYthat is finalized on the same server, for numeric types up to 64 bits,Date,Date32,DateTime,Enum,IPv4,IPv6,UUID, 128-bit integers,String,FixedStringandNullableof them. Sparse columns route only their values. The keys are the same as inuniqExact: the bits of the value for numeric types, and the 128-bitSipHashforString,FixedStringandIPv6(through the newsipHash128Padded, which reads the last partial word of a padded column with one load and is 1.0x to 1.2x faster thanSipHash::update). The slot in the sets is selected by Fibonacci hashing. Controlled by the new settingoptimize_uniq_exact_radix_partitioning(enabled by default, randomized inclickhouse-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.count(DISTINCT UserID)(Q4)count(DISTINCT SearchPhrase)(Q5)count(DISTINCT WatchID)count(DISTINCT URL)count(DISTINCT ClientIP)count(DISTINCT EventTime)count(DISTINCT CounterID)count(DISTINCT UserID)count(DISTINCT SearchPhrase)count(DISTINCT WatchID)count(DISTINCT EventTime)count(DISTINCT CounterID)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,
WatchID0.264 s → 0.037 s.Known gaps: repeat-heavy medium-cardinality inputs (
uniqExact(a)overnumber % 250000or% 500000of 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 onURLandTitle, but a weaker kind of guarantee thanSipHashonce 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
count(DISTINCT x)anduniqExact(x)withoutGROUP BYare 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 settingoptimize_uniq_exact_radix_partitioning.Workflow [PR]
Sync PR [sync-upstream/pr/123552]
Version info
26.11.1.333-master(included in26.11and later)