Skip to content

Skip repeated values of a LowCardinality argument in uniq, uniqExact, uniqHLL12, uniqTheta, min, max and groupUniqArray without GROUP BY - #127940

Merged
Algunenano merged 10 commits into
ClickHouse:masterfrom
groeneai:perf-lc-aggregate-without-key
Nov 11, 2026
Merged

Algunenano merged 10 commits into
ClickHouse:masterfrom
groeneai:perf-lc-aggregate-without-key

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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, max and groupUniqArray of a LowCardinality(String) or LowCardinality(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::prepareAggregateInstructions materializes every LowCardinality argument, so these functions copy and add every row, although a repeated value never changes their state.

Change: a new IAggregateFunction::ignoresRepeatedValues() (like canOptimizeEqualKeysRanges), true for uniq, uniqExact, uniqHLL12, uniqTheta, groupUniqArray and non-float min/max (a repeated NaN can replace a different NaN), forwarded by the -Null wrapper. Not for uniqCombined: its full exact set turns into HLL on any insert. Without keys, a single LowCardinality(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 the groupUniqArray order).

The used values come from a new read-only ColumnLowCardinality::getMinimalDictionary: the same result as getMinimalDictionaryEncodedColumn(...).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 radix uniqExact from #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: lone uniqExact (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

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

groeneai and others added 3 commits October 27, 2026 10:44
…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]>
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ⚠️ groupUniqArray(N) (limited) takes the new path, but no test checks the order in which values are added AGREE, fixed @ 33b2dfa unsorted groupUniqArray(10) LC-vs-plain lines; a reverse-order mutant fails them
2 ⚠️ Tests stay green if the optimization is reverted, so they do not prove the new path runs DISAGREE a mutant that drops one value in the new branch fails the test; staying green on revert is expected for a behaviour-preserving change, speed is covered by the perf test
3 ⚠️ Speed-up and no-regression cases need a paired benchmark DISAGREE paired base/fix A/B (5x5 rounds, 95% CI) incl. mostly distinct, numeric/UUID, small blocks, String, -If, GROUP BY and peak memory: gains on repeated strings, the rest unchanged
4 💡 Changelog entry omits the repeated-values condition AGREE, fixed entry now says "faster when values repeat"
5 ❌ uniqCombined/uniqCombined64 turn a full exact set into HLL on any insert, also of a repeated value, so skipping repeats changed the result (4096 vs 4092 at 4096 distinct values) AGREE, fixed @ 5f389e5 uniqCombined no longer opts in; regression line at the 4096 boundary (LC vs plain)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: SELECT uniqExact(s), min(s) over a 30M-row LowCardinality(String) column with 166 values, Release, 4 threads: 68.5 ms before, 25.7 ms after (5 paired rounds, 95% CI of the ratio [0.368, 0.381]).
b Root cause explained? prepareAggregateInstructions materializes each LowCardinality argument row by row and every row is added, although a repeated value cannot change these states.
c Fix matches root cause? Yes: the column is kept and each value the block uses is added once, in first-occurrence order, so the state is identical; limited to String/FixedString dictionaries of at most half the block, where the mapping pays off (measured).
d Test intent preserved / new tests added? New SQL test comparing LowCardinality and plain columns for all 10 functions, 5 types, 3 block shapes, multi-dictionary blocks and only-NULL input, plus unsorted groupUniqArray(10) lines that see which values are kept and a 4096-value uniqCombined line at its exact-to-HLL switch; existing perf test extended (additions only).
e Both directions demonstrated? Perf A/B base vs fix; the test passes on both (equivalence oracle) and fails on a mutant that drops one value per block, on one that adds the used values in reverse order, and (the uniqCombined line) on the earlier revision that skipped repeats for uniqCombined.
f Fix is general across code paths? Every reader of the instructions checked: only aggregation without keys sets the flag; combinators other than -Null keep today's path; the disabled JIT branch is noted in the commit message.
g Fix generalizes across inputs (params/datatypes/wrappers)? String, FixedString, Nullable(String), UInt32, UUID, IntervalSecond, Nullable(IntervalSecond), block sizes 7-65505, shared and per-block dictionaries; floats excluded for min/max (a repeated NaN changes the result). 560-query differential: 0 mismatches.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, no format or state change; states are identical.
i Invariants and contracts preserved? Same sequence of state-changing inserts (uniqCombined is not marked: its full exact set turns into HLL on any insert); flag set per call and only without keys; the -Null wrapper gets the same ColumnNullable shape as from materialization.

Session id: cron:clickhouse-impl-slot-5:20261027-114800

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c91239]

Summary: ✅


AI Review

Summary

PR #127940, head 8c91239eaf8235a57e723884ba80078e3e2b3111, avoids repeatedly adding identical LowCardinality string values to eligible aggregates without GROUP BY. It shares used dictionary values between aggregates and reuses the lookup for radix uniqExact. No actionable findings remain after reviewing the diff, current code, and all prior discussion. The supplied benchmarks and focused regression tests support the change.

Representation consumers covered:

  • Aggregator::executeWithoutKeyImpl converts retained arguments to ordinary dictionary-value columns before calling aggregates; the Null adapter receives ColumnNullable.
  • Keyed, overflow, and in-order aggregation retain argument materialization through the nonzero-key gate. Adaptive drains build dense arguments independently. Other combinators retain their existing path; window aggregation materializes its arguments separately. Compilation remains disabled for execution without keys.
  • RadixUniqExactRouteTransform::work receives ordinary dictionary-value columns and separates nullable values and their null map before routing.
Missing context / blind spots
  • ⚠️ Current-head CI is still running, with targeted and flaky stateless checks pending. No local ClickHouse binary/build is available, so tests were not rerun locally. Completed current-head CI would close this validation gap; the prior discussion records successful regression and mutation testing and paired performance measurements.
Final Verdict

Status: ✅ Approve from code review. Current-head CI results remain pending.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @Algunenano, could you review this and add the can be tested label so CI runs? Without GROUP BY, the Aggregator now keeps a single LowCardinality(String/FixedString) argument of functions marked by a new IAggregateFunction::ignoresRepeatedValues() (uniq, uniqExact, uniqHLL12, uniqTheta, non-float min/max, groupUniqArray) and adds only the used dictionary values of each block in first-occurrence order, so the state is identical; it is complementary to #127280.

@Algunenano Algunenano self-assigned this Oct 27, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Oct 27, 2026
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]>
@groeneai

groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - be3fee0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this PR: after the upgrade, the background mutation all_1_1_1_2 retries with Unknown expression identifier `b`. Maybe you meant: ['a'] (UNKNOWN_IDENTIFIER), the signature of #120975; the same error is in the Upgrade check of 57 other PRs in 30 days, 0 on master #125293 (external, open)
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 297 of 301 runs since 2026-10-26 22:00 UTC are red, on 237 PRs #126200 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #125293 and #126200 (the owners of the rows above)
CH Inc sync - CH Inc sync (private, not actionable by me)

05453_low_cardinality_aggregate_without_key, which failed the flaky checks on the previous head 5f389e5 because of this PR's own test, passed in all five flaky checks on this head (50 runs each, at most 96 s). CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-220005

@Algunenano Algunenano 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.

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

@Algunenano
Algunenano enabled auto-merge November 5, 2026 17:29
@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

I checked mapUniqueIndexImpl on this PR's head (Release build, clang-22, Xeon 6975P-C, one thread, 30M rows).

The code and assembly are fine for what the function computes. The max pass is vectorized (for UInt8 indexes, four vpmaxub on ymm per 128 bytes). The remap loop is scalar and unrolled 2x. Each row costs 2 loads, 1 store and 2 well-predicted branches, with no calls and no bounds checks, about 0.5 ns per row. Tuning the loop itself buys little: switching to a branchless remap once every value in [min, max] has been seen took uniqExact on a 166-key column from 28-31 to 23-25 ms, and it was 10-15% slower on LowCardinality(Nullable(String)).

The function is still about half of the new path: mapUniqueIndex is ~48% of the query thread's samples in SELECT uniqExact(s) over a 166-key LowCardinality(String) column. And the aggregator does not need most of what it computes. It uses only the dictionary of used values, not the remapped indexes. It still pays for the cut copy, one store per row and a scan of the whole block, while every key has appeared within the first 932 rows of the median 65409-row slice (p99: 1553). I prototyped a read-only scan that stops once every non-default key has been seen, then looks for the null and default keys in the rest with std::find:

Query (30M rows, 1 thread) PR Prototype
uniqExact(s), 166 keys 28-31 ms 16 ms
min(s), max(s), 166 keys 42-48 ms 17 ms
groupUniqArray(s), 166 keys 27-30 ms 14 ms
uniqExact(s), LowCardinality(Nullable(String)), 1000 keys 110-115 ms 100-101 ms
uniqExact(s), shared 8001-key dictionary 45-46 ms 49-50 ms

Reading the 166-key column alone takes 12-16 ms. All results are identical, including the groupUniqArray order. The last row is a regression I have to remove first: a block there has 7999 of the 8001 keys in the median, so the scan never stops early. min(s), max(s) also shows that each aggregate function looks up the used values of the same argument separately in every block.

So it can be improved. I'll do it in a follow-up PR on top of this one and ping you there.

@Algunenano
Algunenano disabled auto-merge November 5, 2026 18:39
@Algunenano

Copy link
Copy Markdown
Member

@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

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. I'll update the branch with master, cut 05453_low_cardinality_aggregate_without_key down and measure it locally with s3 storage, and fold the read-only lookup of the used values into this PR instead of a follow-up (after the merge it can also serve the radix uniqExact path from #127280). I'll reply here once it is pushed.

groeneai and others added 3 commits November 5, 2026 19:39
… 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]>
@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed, head aff387593898:

  • Merged master (b49fce2498a1).
  • 05453 (4d56ccc8d833, aff387593898): the reference tables are Memory now (only t_lc needs a part-wide dictionary), its granules are 10x larger (the slowest query read 301 marks, one GET each), and the controls read Memory tables. Locally on MinIO with randomized settings, the S3 GETs per run went from at most 681 (median 7) to at most 96 (median 2). It also pins count_distinct_optimization = 0, which turned the lone uniqExact lines into a GROUP BY.
  • The lookup (4d56ccc8d833): ColumnLowCardinality::getMinimalDictionary returns the same values in the same order with a read-only scan that stops once every key except the default and NULL has been seen. The aggregator does it once per column and block, and the radix uniqExact uses it too. The loop is one index load and one byte load per row. Release, 1 thread, 30M rows, before/after: uniqExact 31 -> 17-20 ms, min, max 47 -> 18-19 ms, five functions of one column 93 -> 21-23 ms, LowCardinality(Nullable) 153 -> 94 ms, and the 8001-key dictionary that regressed in the prototype 40 -> 39-40 ms. The results are identical, and each of 7 mutants of the new code fails 05453.

I updated the description.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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

162 object files changed (+401.74 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsMinMax.cpp.o 2.65 MiB 2.69 MiB +48.48 KiB (+1.79%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.63 MiB 13.67 MiB +48.06 KiB (+0.34%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupUniqArra… 2.55 MiB 2.58 MiB +33.42 KiB (+1.28%)
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 28.14 MiB 28.17 MiB +31.36 KiB (+0.11%)
src/CMakeFiles/dbms.dir/Columns/ColumnLowCardinality.cpp.o 684.37 KiB 708.48 KiB +24.12 KiB (+3.52%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 13.66 MiB 13.68 MiB +18.86 KiB (+0.13%)

711 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.66, programs/clickhouse-keeper ×0.71 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.6 s 11.3 s +7.6 s (+206%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.5 s +5.3 s (+248%)
Compile time of recompiled translation units

886 translation units recompiled, 8119 s compile time in total, 886 of them have a recent master baseline.

Job report

@snelheidai

Copy link
Copy Markdown

@groeneai one more data point on the lookup in aff38759. When a block uses only part of a UInt8 dictionary, for example a column stored in runs, the early stop never fires and every row goes through the scalar loop. With the two changes below, those queries take half the time; the other cases stay within a few percent.

Time relative to aff38759 (100M rows, 4 threads, Xeon 8375C, 5 paired rounds, 95% intervals within ±3.5%):

LowCardinality(String) data Query aff38759 Unrolled loop + SIMD check
166 keys in runs of 50000 rows (2-3 keys per block) min, max 48 ms 0.89 0.50
same uniq 48 ms 0.88 0.49
same uniqExact (radix) 48 ms 0.88 0.48
94% '', 165 rare keys min, max 81 ms 0.99 0.96
166 keys, uniform min, max 25 ms 1.00 1.03
8000 keys (UInt16 indexes, no SIMD check) min, max 226 ms 0.98 0.99
  • Unrolled loop: the stop test inside the row loop gives the loop a second exit, and clang does not unroll it. Testing the stop once per 64 rows leaves the inner loop with one exit, and #pragma clang loop unroll_count(4) unrolls it.
  • SIMD check (UInt8 indexes, AVX2): 32 indexes at a time are tested against the seen positions, kept as two 16-entry nibble tables for vpshufb. Only a 32-row chunk with an unseen position goes through the loop. Until the early stop fires, the test is extra work, hence 1.03 for the uniform column.

All variants returned identical results: the benchmark queries, a differential check against plain columns (LowCardinality(Nullable(String)) with UInt8 indexes, NULL and the default first appearing late in a block, max_block_size 7 to 65409, groupUniqArray order, one thread), and 05453 (with uniqTheta, which this build lacks, replaced by uniqHLL12). Measured with your commit on master from Nov 3 (ColumnLowCardinality.cpp identical to aff38759), the variants selected by an environment variable in one build.

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]>
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed here (runs of 50000 rows, 1 thread: 58 -> 28 ms): 9d9f1b0cf524 skips the blocks of indexes that repeat the previous row with a vector compare, as the radix uniqExact does, which matches the AVX2 table on runs (0.48 vs 0.46) and also works for wider indexes and on ARM.

@snelheidai

Copy link
Copy Markdown

@groeneai On ARM, the block loop of 9d9f1b0c makes queries 6-8% slower than the loop of aff38759 when blocks use only part of the dictionary and have no runs, so the early stop never fires (first two rows below). With 8000 keys (UInt16 indexes) it costs 3-4% on ARM and x86. Running full blocks through a loop with a constant trip count is faster than both loops on such blocks, mostly removes the UInt16 cost and keeps your run skip.

CPU time relative to the aff38759 loop (100M rows, 4 threads unless noted, 5 rotated rounds, 95% intervals within ±4%):

LowCardinality(String) data Query Graviton 3: 9d9f1b0c Graviton 3: unrolled Xeon 8375C: 9d9f1b0c Xeon 8375C: unrolled
4 keys interleaved per block, 164 in the part min, max 1.08 0.92 0.99 0.87
same, 1 thread min, max 1.06 0.87 0.98 0.84
8000 keys (UInt16 indexes) min, max 1.04 1.00 1.03 1.02
166 keys in runs of 50000 rows min, max 0.75 0.75 0.46 0.45
166 keys, uniform / 94% '' min, max 1.00 / 1.01 1.01 / 0.98 1.00 / 0.99 1.01 / 0.98
LowCardinality(Nullable(String)), 90% NULL uniqExact, min 1.01 1.01 1.02 1.02

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 aff38759 on such blocks (microbenchmark of the copied loops).

All queries return identical results with each loop, and 05453 from 9d9f1b0c passes with each loop on both machines. Each machine ran one build with the loop selected by an environment variable: on ARM, 9d9f1b0c on master from Nov 5; on x86, the build from my previous comment with both loops added.

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]>
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Reproduced on x86 (4 interleaved keys, 1 thread: 0.86 of 9d9f1b0c; 8000 keys: 0.97) and taken as is in c7a356dbe112, which also makes 05453 cover a key that first appears after the last full block.

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c7a356d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / 04653_packed_part_size_accounting_no_read_in_commit flaky, not in this PR's diff: fewer_file_open 0 instead of 1, 111 of 111 reruns passed; the same failure hit 24 other PRs and 4 master runs in the last 30 days #118234 (mine, open)
Mergeable Check / PR praktika rollups of the row above #118234 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261106-093004

@Algunenano
Algunenano enabled auto-merge November 11, 2026 12:43
@Algunenano
Algunenano added this pull request to the merge queue Nov 11, 2026
Merged via the queue into ClickHouse:master with commit c40120a Nov 11, 2026
187 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 11, 2026
perfloop-agent pushed a commit to perfloop-oss/ClickHouse that referenced this pull request Nov 20, 2026
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]>
perfloop-agent pushed a commit to perfloop-oss/ClickHouse that referenced this pull request Nov 20, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors 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.

uniq*, min and max of a LowCardinality column without GROUP BY: add only the distinct dictionary values of each block

4 participants