Skip to content

Optimize aggregate functions uniqHLL12 and uniqCombined - #109831

Merged
CurtizJ merged 4 commits into
ClickHouse:masterfrom
CurtizJ:optimize-uniqHLL
Jul 21, 2026
Merged

CurtizJ merged 4 commits into
ClickHouse:masterfrom
CurtizJ:optimize-uniqHLL

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Optimized aggregate functions uniqHLL12 and uniqCombined.

Additional Context

Just rewrite suboptimal code in HyperLogLogCounter.

Based on #109794. I opened it in a separate PR because I want to check the perf tests of this change isolated after #109794 is merged.

Version info

  • Merged into: 26.7.1.1300 (included in 26.7 and later)

Overallocate the bitset of `CompactArray` by one padding byte and access
cells through an unaligned little-endian 16-bit word, which is always in
bounds and always covers a whole cell. This removes the one-byte/two-byte
branch of `Locus`, which is unpredictable on random buckets (~50/50 for
6-bit cells) and dominated the cost of `HyperLogLogCounter::update`
(2.76x on the isolated update loop).

The serialized format is unchanged: the new method `getSerializableState`
returns a `std::span` over the bitset without the trailing padding byte,
and `HyperLogLogCounter` now serializes field-wise (rank store, then
denominator, then the number of zeros) instead of dumping the raw object.
Verified byte-identical: state dumps from the old and new binaries match,
and a cross-binary write/read matrix returns identical results.

Remove `Locus` and `Reader` entirely: their last real consumer,
`readAndMerge`, was removed in 7521fd2, and since then they were
referenced only by the example, which is rewritten to the new interface.

`uniqHLL12` speeds up by 12-28% on hits_100m (it has no batch insertion
path, so it is reachable only by this change), `uniqCombined` and
`uniqCombined64` by up to 23% without GROUP BY and up to 12% with GROUP BY
on low-cardinality keys; no regressions.

Co-Authored-By: Claude Fable 5 <[email protected]>
@CurtizJ CurtizJ changed the title Optimize uniq hll Optimize aggregate functions uniqHLL12 and uniqCombined Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ea66303]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR rewrites CompactArray, changes the HyperLogLogCounter serialization plumbing to keep the on-disk layout stable, and batches uniqCombined hashing/insertion work for performance. The CompactArray/HLL changes look directionally sound, but the new consecutive-duplicate collapse in AggregateFunctionUniqCombined::addBatchImpl breaks the estimator's exact-set-to-HLL promotion contract, so this should not merge as-is.

Findings

❌ Blockers

  • [src/AggregateFunctions/AggregateFunctionUniqCombined.h:259] uniqCombined now drops consecutive duplicate rows before calling CombinedCardinalityEstimator::insertMany. That changes the contract at the medium/HLL threshold: with uniqCombinedState(12) over 0..254, 255, 255, the scalar path inserts the first 255, reaches the 256-element medium set, and the second 255 promotes to HLL; this batched path hashes only one trailing 255, stays in the exact medium set, and serializes a different state. The fix needs to preserve row multiplicity until after the medium-to-large transition point, and the same boundary case should be covered by a regression test.
Tests
  • ⚠️ Add a focused regression for the threshold case above, ideally on uniqCombinedState(12) / uniqCombined64State(12), so the batched path proves it still promotes to HLL after the exact set fills and then sees another row with the same value.
Final Verdict

Status: ❌ Block

  • Preserve the medium-to-large promotion semantics when batching consecutive equal values in uniqCombined.
  • Add a focused regression test around the 256-element boundary so the bug does not reappear through another batching optimization.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This PR rewrites the uniqCombined aggregate hashing and makes the HyperLogLog CompactArray rank store use branchless 16-bit access, so its effect should land on COUNT(DISTINCT ...) queries. Q4 (COUNT(DISTINCT UserID)) shows a -17.3% improvement that is directly on this hot path and consistent with the change, but it stays within master's current variance band [200,282 ms], so it is reported as no change rather than a confirmed win. Q15 is a plain GROUP BY UserID aggregation the PR does not touch; its flagged -21.3% improvement has no plausible cause here, so it is downgraded to inconclusive as measurement noise.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 244 192 -21.3% <0.0001 aggregation: Q15 is a plain GROUP BY UserID with no COUNT DISTINCT, so a uniqCombined-only change cannot explain this -21.3% shift; treat it as run-to-run variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2154ca3b-b21f-4521-9d96-94dbfba0704d
  • MIRAI run: e9def500-e6a2-4517-9d80-f67fdc213f05
  • PR check IDs:
    • clickbench_486393_1783990449
    • clickbench_486406_1783990449
    • clickbench_486412_1783990449
    • tpch_adapted_1_official_486418_1783990449
    • tpch_adapted_1_official_486424_1783990449
    • tpch_adapted_1_official_486431_1783990449

CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Jul 8, 2026
`hashOne` returned `HashValueType`, truncating `CityHash64` to 32 bits
for `String` and `IPv6`, while `Data::Key` is deliberately `UInt64` for
these types: plain `uniqCombined` keeps the full 64-bit hash for them
for compatibility of aggregate function states. Return `Key` instead,
restoring states byte-identical to master; fixes the failures of test
02751_ip_types_aggregate_functions_states.

Suggested in: ClickHouse#109831 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@CurtizJ

CurtizJ commented Jul 9, 2026

Copy link
Copy Markdown
Member Author

From perf dashboard:

Screenshot 2026-07-09 at 03 13 04 Screenshot 2026-07-09 at 03 13 30

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 90/104 (86.54%) · Uncovered code

Full report · Diff report

@CurtizJ

CurtizJ commented Jul 14, 2026

Copy link
Copy Markdown
Member Author

@CurtizJ
CurtizJ requested a review from novikd July 15, 2026 14:29

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

LGTM

Comment thread src/Common/CompactArray.h
Comment on lines +62 to +63
/// The last byte is padding for the branchless 16-bit access; it stays zero and is not serialized.
UInt8 bitset[BITSET_SIZE + 1] = { 0 };

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.

If we know BITSET_SIZE in the compile time, then we can calculate the needed array size in the compile time as well. IDK if it was doing to save 1 byte for some cases.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Do you mean that we can avoid allocating 1 extra byte if we know in advance that we won't hit the tail? I think it's not worth it.

@CurtizJ
CurtizJ added this pull request to the merge queue Jul 21, 2026
Merged via the queue into ClickHouse:master with commit 60fb246 Jul 21, 2026
175 of 177 checks passed
@CurtizJ
CurtizJ deleted the optimize-uniqHLL branch July 21, 2026 21:31
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 21, 2026
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Aug 27, 2026
Building master with -DENABLE_BENCHMARKS=ON failed to compile
src/Storages/benchmarks/benchmark_statistics.cpp with two errors of the
form "template argument for template type parameter must be a type" at
lines 48 and 50.

Two changes landed from branches that never saw each other. ClickHouse#109831
(ea66303) gave AggregateFunctionUniqCombined a ColumnType
template parameter in second position, making it
  template <typename T, typename ColumnType, UInt8 K, typename HashValueType>
ClickHouse#111221 (40da35b, "Reduce binary size for microbenchmark") then
replaced registerAggregateFunctions() in this benchmark with a
benchmark-local factory that hand-instantiates the class using the old
three-argument spelling. The literal 12 therefore binds to the ColumnType
position, where a type is required.

Supply the missing argument at the two call sites, using the spelling the
real factory uses for numeric types (AggregateFunctionUniqCombined.h:373,
ColumnVector<TYPE>). This is behaviour-preserving rather than a choice
among candidates: before ClickHouse#109831 the class hardcoded
assert_cast<const ColumnVector<T> &>(*columns[0]) in its body, and that
commit only hoisted the hardcoded type into the new parameter.

No CI job caught this because ENABLE_BENCHMARKS defaults to OFF
(CMakeLists.txt:159) and grep -rn ENABLE_BENCHMARKS ci/ returns no hits,
so no build compiles this translation unit.

Validated in both directions: on the unmodified tree the target fails with
exactly those two errors and no others; with this change it compiles,
links, and the four UniqV2 benchmark cases run, covering both the UInt64
and Float64 paths. The other eight benchmark targets compile cleanly, so
all nine benchmark executables now build.

Closes: ClickHouse#116251
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`hashOne` returned `HashValueType`, truncating `CityHash64` to 32 bits
for `String` and `IPv6`, while `Data::Key` is deliberately `UInt64` for
these types: plain `uniqCombined` keeps the full 64-bit hash for them
for compatibility of aggregate function states. Return `Key` instead,
restoring states byte-identical to master; fixes the failures of test
02751_ip_types_aggregate_functions_states.

Suggested in: ClickHouse#109831 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Optimize aggregate functions `uniqHLL12` and `uniqCombined`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants