Repository navigation
Skip repeated values of a LowCardinality argument in uniq, uniqExact, uniqHLL12, uniqTheta, min, max and groupUniqArray without GROUP BY - #127940
Conversation
…nd groupUniqArray without GROUP BY Aggregator::prepareAggregateInstructions materializes every LowCardinality argument (recursiveRemoveLowCardinality), so aggregation without keys copies and adds every row. For functions whose state does not change when it gets a value it already has, the repeats are wasted work. New IAggregateFunction::ignoresRepeatedValues(), next to canOptimizeEqualKeysRanges(): true for AggregateFunctionUniq (uniq, uniqExact, uniqHLL12, uniqTheta) and its variadic fallback, uniqCombined(64), groupUniqArray and min/max of non-float types, forwarded by the -Null wrapper. Floating point is excluded for min/max: with two NaN payloads a and b, min/max over [a, b, a] returns a and over [a, b] returns b. Without keys, a single LowCardinality argument of such a function is kept, marked by AggregateFunctionInstruction::has_low_cardinality_argument, and addBatchSinglePlace adds the dictionary values of getMinimalDictionaryEncodedColumn(row_begin, rows). Both index-mapping paths number the used values in the order of their first occurrence, so the state-changing inserts are the same as for all rows and the state is identical (including groupUniqArray order and approximate estimates). The column is kept only for String/FixedString dictionaries of at most half the block rows. Measured without these limits (Release, 4 threads): min/max of LowCardinality(UInt32) 1.15x slower, a part-wide 8001-value dictionary read in 1000-row blocks 1.8-3.0x slower, and mostly distinct blocks slightly slower. With them those cases are unchanged and, e.g., uniqExact+min of a 166-value column takes 0.38x the time. The JIT branch of executeWithoutKeyImpl reads batch_arguments directly; it is disabled (use_compiled_functions = false), and must skip such instructions if it is ever enabled. Closes ClickHouse#127916 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…me values Co-Authored-By: Claude Opus 5.5 <[email protected]>
…L on any insert CombinedCardinalityEstimator converts a full medium hash set (4096 entries for string arguments at the default K = 17) into HLL on the next insert, before the duplicate check. Skipping repeated values kept a LowCardinality column exact (4096) where the same rows in an ordinary column give the HLL estimate (4092 or 4088, depending on the rows). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 rounds, 5 findings, the last round clean) plus my own review.
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261027-114800 |
|
Workflow [PR], commit [8c91239] Summary: ✅
AI ReviewSummaryPR #127940, head Representation consumers covered:
Missing context / blind spots
Final VerdictStatus: ✅ Approve from code review. Current-head CI results remain pending. |
|
cc @nihalzp @Algunenano, could you review this and add the |
The flaky check runs 8 copies of the test at once and it took 78-180 s per run, up to the 600 s timeout. Its query_log shows where the time went: the max_block_size = 7 MergeTree comparisons (55 s per run, up to 500 s with use_streaming_marks_compression and local_filesystem_read_prefetch) and the two OPTIMIZE FINAL (24 s). With a mutant that adds nothing on the kept path, the 7-row, `% 97` and `lc 1000 % 3` comparisons never fail: their dictionaries are larger than half the block, so they only check the unchanged path. Drop them. Memory ignores max_block_size, so one `mem` comparison per filter is enough. Each INSERT now runs with max_insert_threads = 1, which leaves one part per table, so OPTIMIZE FINAL is not needed for the part-wide dictionary. Per run: server CPU 0.38 s instead of 1.13 s. On the kept-nothing mutant the test still fails 20/20 randomized runs, and the reverse-order mutant still fails both `limit` lines. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - be3fee0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261027-220005 |
Algunenano
left a comment
There was a problem hiding this comment.
Looks good and it makes sense. As a separate task, could you verify the performance of mapUniqueIndexImpl in case we can improve it to reduce the impact of looking for them? Just reply here if the code and assembly is good, or create a followup and ping me if not. Thanks
|
I checked The code and assembly are fine for what the function computes. The max pass is vectorized (for The function is still about half of the new path:
Reading the 166-key column alone takes 12-16 ms. All results are identical, including the So it can be improved. I'll do it in a follow-up PR on top of this one and ping you there. |
|
@groeneai There are some issues with the sync: 05453_low_cardinality_aggregate_without_key takes too long with s3 storage. Could you reduce it? Other failures are unrelated but require updating with master. Considering this we could add the alternative to mapUniqueIndexImpl here instead of a followup |
|
Thanks. I'll update the branch with master, cut |
… indexes Without GROUP BY, functions that ignore repeated values add only the dictionary values used by the block, and a lone uniqExact routes only those values to its radix partitions. Both took them from getMinimalDictionaryEncodedColumn, which copies the indexes, scans the whole range and stores a remapped index per row, though only the dictionary is used. getMinimalDictionary returns the same values in the same order (first occurrence) with a read-only scan that stops once every regular key has been seen, then looks for the default and NULL in the rest of the rows. A dictionary larger than the range keeps the old path. The Aggregator looks the values up once per argument column and block, shared between functions. Measured on a Release build, max_threads = 1, 30M rows, base/new median: uniqExact of 166 keys 31-32/17-20 ms, min + max 47-48/18-19, five functions on one column 93/21-23, LowCardinality(Nullable) 153-154/94-95, an 8001-key dictionary without early stop 40-41/39-40 (radix) and 65-66/49-50 (Aggregator). Results identical for all 13 queries. 05453 also gets cheaper on object storage: the reference tables are Memory (only t_lc needs a part-wide dictionary), the MergeTree granules are 10x larger, and the controls read Memory tables. Locally on MinIO this cuts the S3 GETs per run from at most 681 (median 7) to at most 96 (median 2) over 41-42 randomized runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t to a GROUP BY A randomized count_distinct_optimization = 1 turned the lone uniqExact lines into count() over GROUP BY, so they did not reach the radix uniqExact. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Pushed, head
I updated the description. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes162 object files changed (+401.74 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units886 translation units recompiled, 8119 s compile time in total, 886 of them have a recent master baseline. |
|
@groeneai one more data point on the lookup in Time relative to
All variants returned identical results: the benchmark queries, a differential check against plain columns ( Patch on aff3875 (without the AVX2 overload it is the unrolled loop only)--- a/src/Columns/ColumnLowCardinality.cpp
+++ b/src/Columns/ColumnLowCardinality.cpp
@@ -1,5 +1,9 @@
#include <Columns/ColumnLowCardinality.h>
+#if defined(__AVX2__)
+#include <immintrin.h>
+#endif
+
#include <Columns/ColumnString.h>
#include <Columns/ColumnsNumber.h>
#include <DataTypes/IDataType.h>
@@ -136,6 +140,99 @@
throw Exception(ErrorCodes::LOGICAL_ERROR, "Indexes column for getUniqueIndex must be ColumnUInt, got {}", column.getName());
}
+ /// Marks the positions of `data[row, end)` in `seen` and appends each new one to `positions`, until the position that
+ /// makes `regular_left` zero. Returns the row where the scan stopped. The stop is tested once per 64 rows, so that
+ /// the inner loop has one exit and can be unrolled.
+ template <typename T>
+ NO_INLINE size_t scanUsedPositions(
+ const T * __restrict data, size_t row, size_t end, UInt8 * __restrict seen, T * __restrict positions,
+ size_t & num_positions, size_t num_special_positions, size_t & regular_left)
+ {
+ static constexpr size_t chunk = 64;
+ size_t n = num_positions;
+ size_t left = regular_left;
+ while (row < end)
+ {
+ const size_t chunk_end = std::min(end, row + chunk);
+ size_t found_regular = 0;
+#pragma clang loop unroll_count(4)
+ for (; row < chunk_end; ++row)
+ {
+ const T position = data[row];
+ if (!seen[position]) [[unlikely]]
+ {
+ seen[position] = 1;
+ positions[n++] = position;
+ found_regular += position >= num_special_positions;
+ }
+ }
+ if (found_regular >= left)
+ {
+ left = 0;
+ break;
+ }
+ left -= found_regular;
+ }
+ num_positions = n;
+ regular_left = left;
+ return row;
+ }
+
+#if defined(__AVX2__)
+ /// The same for `UInt8` indexes, but 32 rows at a time are first tested against the set of seen positions (a 256-bit
+ /// set kept as two 16-entry nibble tables for `vpshufb`): only a chunk with an unseen position goes through the loop.
+ NO_INLINE size_t scanUsedPositions(
+ const UInt8 * __restrict data, size_t row, size_t end, UInt8 * __restrict seen, UInt8 * __restrict positions,
+ size_t & num_positions, size_t num_special_positions, size_t & regular_left)
+ {
+ alignas(16) UInt8 table_low[16] = {}; /// table_low[v & 15] has bit (v >> 4) for seen v < 128
+ alignas(16) UInt8 table_high[16] = {}; /// table_high[v & 15] has bit ((v >> 4) - 8) for seen v >= 128
+ size_t n = num_positions;
+ size_t left = regular_left;
+ const __m256i nibble = _mm256_set1_epi8(0x0f);
+ const __m256i seven = _mm256_set1_epi8(7);
+ const __m256i bits = _mm256_setr_epi8(
+ 1, 2, 4, 8, 16, 32, 64, static_cast<char>(128), 1, 2, 4, 8, 16, 32, 64, static_cast<char>(128),
+ 1, 2, 4, 8, 16, 32, 64, static_cast<char>(128), 1, 2, 4, 8, 16, 32, 64, static_cast<char>(128));
+ __m256i low = _mm256_setzero_si256();
+ __m256i high = _mm256_setzero_si256();
+ for (; row + 32 <= end; row += 32)
+ {
+ const __m256i v = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(data + row));
+ const __m256i lo = _mm256_and_si256(v, nibble);
+ const __m256i hi = _mm256_and_si256(_mm256_srli_epi16(v, 4), nibble);
+ const __m256i row_bits
+ = _mm256_blendv_epi8(_mm256_shuffle_epi8(low, lo), _mm256_shuffle_epi8(high, lo), _mm256_cmpgt_epi8(hi, seven));
+ const __m256i hit = _mm256_and_si256(row_bits, _mm256_shuffle_epi8(bits, hi));
+ if (_mm256_movemask_epi8(_mm256_cmpeq_epi8(hit, _mm256_setzero_si256())) == 0)
+ continue;
+ for (size_t i = row; i < row + 32; ++i)
+ {
+ const UInt8 position = data[i];
+ if (seen[position])
+ continue;
+ seen[position] = 1;
+ positions[n++] = position;
+ if (position < 128)
+ table_low[position & 15] |= static_cast<UInt8>(1u << (position >> 4));
+ else
+ table_high[position & 15] |= static_cast<UInt8>(1u << ((position >> 4) - 8));
+ if (position >= num_special_positions && --left == 0)
+ {
+ num_positions = n;
+ regular_left = 0;
+ return i + 1;
+ }
+ }
+ low = _mm256_broadcastsi128_si256(_mm_load_si128(reinterpret_cast<const __m128i *>(table_low)));
+ high = _mm256_broadcastsi128_si256(_mm_load_si128(reinterpret_cast<const __m128i *>(table_high)));
+ }
+ num_positions = n;
+ regular_left = left;
+ return scanUsedPositions<UInt8>(data, row, end, seen, positions, num_positions, num_special_positions, regular_left);
+ }
+#endif
+
/// Returns the positions used by `indexes[begin, end)` in the order of their first occurrence, the same list as `mapUniqueIndex`.
template <typename T>
MutableColumnPtr getUsedPositions(
@@ -153,19 +250,7 @@
if (dictionary_size > num_special_positions)
{
size_t regular_left = dictionary_size - num_special_positions;
- for (; row < end; ++row)
- {
- const T position = data[row];
- if (seen_data[position])
- continue;
- seen_data[position] = 1;
- positions[num_positions++] = position;
- if (position >= num_special_positions && --regular_left == 0)
- {
- ++row;
- break;
- }
- }
+ row = scanUsedPositions(data, row, end, seen_data, positions, num_positions, num_special_positions, regular_left);
}
/// Only the special positions (the default and NULL) can occur first in the rest of the rows. |
…d values of a LowCardinality column When a block uses only part of its dictionary, for example a sorted column read with the part-wide dictionary, the lookup never stops early and every row went through the scalar loop. Now 32 bytes of indexes equal to the rows before them are skipped with one vector compare (the duplicate skip of the radix uniqExact does the same), and the stop is tested once per block, so the inner loop has one exit. Release, Xeon 6975P-C, 100M rows, CPU time, 4 rotated rounds, before/after, 1 thread: 166 keys in runs of 50000 rows, min/max 58.3 -> 28.0 ms, uniq 57.6 -> 27.4, LowCardinality(Nullable) 58.7 -> 28.2; 4 threads 0.67. Uniform 166 keys, 94% '' and 8000 keys (UInt16 indexes): 0.97-1.02. Identical results. The AVX2 nibble-table check suggested on the PR gives the same on runs (0.46) and is also faster when a block interleaves a few keys (0.69 vs 0.97), but only for UInt8 indexes on x86. 05453 gets a Memory table with sorted runs (64 rows, aligned with the compared blocks, and 50 rows with NULL and the default), with half of the dictionaries used and all of them. It fails on each of the mutants "skip a block that is uniform but differs from the previous row", "stop one value early" and "count NULL and the default as regular values". The perf test gets test_lc_runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Confirmed here (runs of 50000 rows, 1 thread: 58 -> 28 ms): |
|
@groeneai On ARM, the block loop of CPU time relative to the
With a constant trip count, clang unrolls the block, so a row costs two loads and a not-taken branch. The variable-length loop adds a counter and an exit test per row. On Graviton 3, that loop and the skip test made the lookup alone 1.16-1.33x slower than the loop of All queries return identical results with each loop, and Tables (MergeTree ORDER BY x, one part of 100M rows each)-- 4 keys interleaved per block, 164 in the part
INSERT INTO lcsub4 SELECT number, concat('k', toString(intDiv(number, 2000000) % 41 * 4 + number % 4)) FROM numbers(1e8);
-- 8000 keys
INSERT INTO lc10k SELECT number, concat('value ', toString(cityHash64(number) % 8000)) FROM numbers(1e8);
-- runs
INSERT INTO lcrun SELECT number, concat('model ', toString(intDiv(number, 50000) % 166)) FROM numbers(1e8);
-- uniform
INSERT INTO lc166 SELECT number, concat('model ', toString(number * 7919 % 166)) FROM numbers(1e8);
-- 94% ''
INSERT INTO lcskew SELECT number, if(cityHash64(number) % 100 < 94, '', concat('model ', toString(cityHash64(number, 1) % 165))) FROM numbers(1e8);
-- LowCardinality(Nullable(String))
INSERT INTO lcnull SELECT number, number % 10 ? NULL : toString(number % 10000) FROM numbers(1e8);Patch on 9d9f1b0--- a/src/Columns/ColumnLowCardinality.cpp
+++ b/src/Columns/ColumnLowCardinality.cpp
@@ -157,28 +157,46 @@
constexpr size_t block_size = 32 / sizeof(T);
while (row < end)
{
- const size_t block_end = std::min(row + block_size, end);
- if (row != begin && block_end - row == block_size)
+ size_t found_regular = 0;
+ if (end - row >= block_size)
{
- bool all_same = true;
+ if (row != begin)
+ {
+ bool all_same = true;
+ for (size_t i = 0; i < block_size; ++i)
+ all_same &= data[row + i] == data[row + i - 1];
+ if (all_same)
+ {
+ row += block_size;
+ continue;
+ }
+ }
+
+ /// A constant trip count lets the block be unrolled, without a counter and an exit test per row.
+#pragma clang loop unroll(full)
for (size_t i = 0; i < block_size; ++i)
- all_same &= data[row + i] == data[row + i - 1];
- if (all_same)
{
- row = block_end;
- continue;
+ const T position = data[row + i];
+ if (!seen_data[position]) [[unlikely]]
+ {
+ seen_data[position] = 1;
+ positions[num_positions++] = position;
+ found_regular += position >= num_special_positions;
+ }
}
+ row += block_size;
}
-
- size_t found_regular = 0;
- for (; row < block_end; ++row)
+ else
{
- const T position = data[row];
- if (!seen_data[position]) [[unlikely]]
+ for (; row < end; ++row)
{
- seen_data[position] = 1;
- positions[num_positions++] = position;
- found_regular += position >= num_special_positions;
+ const T position = data[row];
+ if (!seen_data[position])
+ {
+ seen_data[position] = 1;
+ positions[num_positions++] = position;
+ found_regular += position >= num_special_positions;
+ }
}
}
if (found_regular >= regular_left) |
…nality column A block of 32 bytes of indexes now goes through a loop with a constant trip count, which clang unrolls, so a row costs two loads and a not-taken branch. The rows after the last full block go through the per-row loop. The run skip and the once-per-block stop test stay. With the variable trip count of 9d9f1b0, a block that uses a few keys of a larger dictionary, so the lookup never stops early, was 2-3% slower than before the run skip on x86, and 6-8% slower on Graviton 3 as measured on the PR. Release, Xeon 6975P-C, 100M rows in one part, CPU time, 6 rotated rounds, relative to 9d9f1b0: 4 keys interleaved per block (164 in the part), min/max, 1 thread 0.86 (aff3875: 0.98), 4 threads 0.88-0.89, uniq 0.91; 8000 keys (UInt16 indexes) 0.97 (aff3875: 0.97); 166 keys in runs of 50000 rows 0.91-0.97, the run skip is kept; uniform 166 keys, 94% '', LowCardinality(Nullable) with 90% NULL: 0.95-0.98. Identical results. Suggested by snelheidai on the PR, who measured the same on Graviton 3 and on a Xeon 8375C. The same loop through a lambda shared with the tail compiles to the same unrolled block and was 2% slower at 1 thread, so the body stays written out twice. 05453: the `runs` line with half of the dictionaries now ends 6 rows into a run of s, so a key that first appears after the last full block is checked, and t_runs is inserted with max_block_size = 30000, so a random max_block_size cannot split it into blocks that move those boundaries. It fails on the mutant that drops those rows, and still fails on the three mutants of the previous commit, with max_block_size 8000, 8993, 10000, 30000, 65505 and 100000. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Reproduced on x86 (4 interleaved keys, 1 thread: 0.86 of |
CI finish ledger - c7a356dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261106-093004 |
Without keys, `Aggregator::prepareAggregateInstructions` materialized every
constant argument to the size of the block. For
`COUNTOrDefaultDistinct(toFixedString('', 1048577))` with
`max_block_size = 65409` that is a 64 GiB request in each
`AggregatingTransform` thread: the AST fuzzer run on PR ClickHouse#99639 had 16 of
them, and the server was OOM-killed at 44 GB RSS.
A function whose state ignores repeated values (`ignoresRepeatedValues()`,
added by ClickHouse#127940) gets the same state from one row as from every row of a
constant. So, without keys, a single constant argument of such a function is
now passed as its one-row data column and added once per block, the way
ClickHouse#127940 adds the used values of a `LowCardinality` argument and the radix
partitioned `uniqExact` routes a constant once per block.
`-Distinct` forwards to the nested function only the values it has not seen,
so it ignores repeated values whatever the nested function is. It now reports
it, which also gives it the `LowCardinality` path without keys.
The JIT branch of `executeWithoutKeyImpl` is not affected: its only caller
passes `use_compiled_functions = false`.
CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=00b62ef53d2811d1f363572394dbf8b9bb9ab2d7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous last query of 05628 compared a LowCardinality column with its plain copy, which gives the same result on master, so it could not show that -Distinct now reports ignoresRepeatedValues() and takes the LowCardinality path of ClickHouse#127940. The new query runs -Distinct functions over a materialized LowCardinality(FixedString(100000)) column under a 100 MB query limit: master converts it to a full column (an 8 GiB request, MEMORY_LIMIT_EXCEEDED), the fix adds its one used value. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Without
GROUP BY,uniq,uniqExact,count(DISTINCT),uniqHLL12,uniqTheta,min,maxandgroupUniqArrayof aLowCardinality(String)orLowCardinality(FixedString)column are faster when values repeat: each distinct value of a block is added once instead of every row (up to 14x faster for columns with few distinct values).Description
Closes #127916 (analysis by @ snelheidai).
Aggregator::prepareAggregateInstructionsmaterializes everyLowCardinalityargument, so these functions copy and add every row, although a repeated value never changes their state.Change: a new
IAggregateFunction::ignoresRepeatedValues()(likecanOptimizeEqualKeysRanges), true foruniq,uniqExact,uniqHLL12,uniqTheta,groupUniqArrayand non-floatmin/max(a repeatedNaNcan replace a differentNaN), forwarded by the-Nullwrapper. Not foruniqCombined: its full exact set turns into HLL on any insert. Without keys, a singleLowCardinality(String|FixedString)argument of such a function is kept when its dictionary has at most half the block rows, and the function gets only the used values in the order of their first occurrence, so the state is the same as after adding every row (also thegroupUniqArrayorder).The used values come from a new read-only
ColumnLowCardinality::getMinimalDictionary: the same result asgetMinimalDictionaryEncodedColumn(...).dictionary, but it stops once every key except the default and NULL has been seen, then looks for those two in the rest of the rows. Blocks of indexes that repeat the previous row (a sorted column) are skipped with a vector compare. A dictionary larger than the range keeps the old path. Functions of the same column share it per block, and the radixuniqExactfrom #127280 uses it too.Validation, Release A/B, fix/base. 4 threads: 166 values with 94%
''0.24-0.50; 166 uniform values 0.07-0.23;FixedString(16)0.17-0.49;Nullable, 90% NULL 0.46-0.60; 10000 values 0.66-0.89. The lookup alone, before/after, 1 thread, 30M rows: loneuniqExact(radix) 31 -> 17-20 ms, five functions of one column 93 -> 21-23 ms, an 8001-key dictionary used almost fully 40 -> 39-40 ms. 166 keys in runs of 50000 rows, 100M rows, 1 thread: 58 -> 28 ms with the skip. Mostly distinct values, numeric columns,String,-If,GROUP BY: unchanged. Results are identical.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/127940]
Version info
26.11.1.1991-master(included in26.11and later)