Skip to content

Grouped uniqExact skips a row that repeats the previous row's group and value - #128190

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:uniq-exact-grouped-skip-repeats
Oct 30, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:uniq-exact-grouped-skip-repeats

Conversation

@groeneai

@groeneai groeneai commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128138
Related: #124126

Changelog category (leave one):

  • Performance Improvement

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

uniqExact and COUNT(DISTINCT) with GROUP BY are faster on data where consecutive rows often have the same group and value, as in data sorted by these columns: such a row is no longer inserted into the set again. ClickBench Q9 and Q10 are 1.16x and 1.14x faster with 4 threads.

Description

Grouped uniqExact inserted every row into its group's set, also a row whose group and value equal the previous row's. That insert never changes the set, and in sorted data it is common: 77% of the rows of ClickBench hits repeat the previous (RegionID, UserID). Now a 256-row chunk's keys are collected without those rows (branch-free for numbers; a skipped String or IPv6 is not hashed), then inserted. When at most half of the rows seen so far in the block repeated, the rest of the block takes the existing per-row loop, like the keyless addManyChunked. Without that fallback (the patch in #128138) CPU time grows by up to 25% on repeat-free data whose sets fit in the cache.

Xeon 6975P-C, matched ThinLTO builds, 12 rounds, ratio to master:

4 threads 64 threads 192 threads
Q9, wall time 0.87 0.92 0.92
Q10, wall time 0.88 0.92 0.91
slowest repeat-free case, CPU time 1.01 (16 threads) 1.01 1.01

The drawback cases (unsorted hits, no repeats with small or large sets, 200K groups in random order, forced two-level aggregation, filtered blocks, 50-67% repeats) are within 1.5% of master; results are identical. Graviton3, 4 threads (#128138): Q9 1.16x, Q10 1.13x faster, repeat-free cases within 1.2%. Not measured on AMD EPYC; the new uniq_with_key.xml query adds the worst case to CI perf tests.

Only the grouped batch path of single-argument uniqExact (also with -If) of native numbers, Enum, Date, Date32, DateTime, UUID, IPv4, IPv6, String and FixedString changes; plain uniqExact of Decimal, DateTime64, Nullable or several arguments keeps the per-row loop. Unlike #93268 (reverted in #93294), no state is added and the keyless path is untouched.

Analysis and first patch: @ snelheidai, #128138.


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

Version info

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

groeneai and others added 2 commits October 29, 2026 14:47
`uniqExact` / `COUNT(DISTINCT)` with GROUP BY inserted every row into its
group's set, also a row whose group and value equal the previous row's,
which is common in data sorted by these columns (ClickBench `hits`: 77% of
rows repeat the previous (RegionID, UserID)). Inserting a key the set
already contains never changes it, so such rows are dropped before the
insert (and, for String/IPv6, before hashing). Numeric keys are collected
branch-free.

Like the keyless last-value cache (`addManyChunked`), the skip is adaptive:
when at most half of the rows seen so far in the batch repeat, the rest of
the batch goes through the per-row loop, so data without repeats keeps its
current speed.

Based on the analysis and patch in ClickHouse#128138.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… to uniq_with_key.xml

The overflow query of 05472 gets `uniqExact(number)` (no row repeats, so
every block reaches the per-row fallback) and `max_block_size = 1024`:
blocks that hold two keys take `addBatchWithNonNullPlaces` (the block where
k = 1 appears) and `addBatch` with null places (the block where k = 2 is
dropped), while a block with one key and `max_threads = 1` would go through
`addBatchSinglePlace`. The expected values do not change.

`uniq_with_key.xml` gets the cache-resident worst case without repeats (one
group per 65536 rows, the value changes every row), so the CI performance
comparison watches the fallback on both CI machines.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (head 9777aab): 0 open findings

Gate B (codex), 3 runs on the same code; the PR description was corrected between runs.

  • ⚠️ Decimal* and DateTime64 use AggregateFunctionUniqVariadic and are not sped up: AGREE on the description, which now names the exact types; extending the variadic path is a separate change (nothing regresses there).
  • ⚠️ A single 8-bit key (lookup table) and sparse arguments take per-row paths: AGREE on the description, which no longer claims anything about them; under top-K or max_rows_to_group_by an 8-bit key does reach the new code.
  • ⚠️ "No added test tells the optimization apart from master": DISAGREE. A skipped insert is not observable from SQL; the stateless test checks that results do not change and turns red under 7 mutations of the skip and fallback logic. The gain is measured by existing CI perf queries (uniq.xml uniqExact(UserID) ... GROUP BY RegionID, clickbench.xml Q9/Q10); the new uniq_with_key.xml query guards the repeat-free worst case.
  • 💡 Noted, not blocking: the test has no -0./0. adjacency line, and a set converts to two-level inside the new loop only with 2 threads.

Final run: 0 findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat, could you review this and add the can be tested label so CI runs? Grouped uniqExact now skips the insert for a row whose place and value equal the previous row's (branch-free for numbers, no hash for String/IPv6), and falls back to the per-row loop once at most half of a block's rows repeat, so repeat-free data keeps master's speed (measured up to 192 threads in #128138).

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e0c5f4]

Summary: ✅


AI Review

Summary

PR #128190, reviewed at 4e0c5f4b, optimizes grouped uniqExact by skipping repeated state/value pairs and reverting to per-row insertion when repeats are uncommon. No actionable findings. The new stateless test passed locally with all 62 output lines matching the reference; the linked measurements support the performance claim.

Missing context / blind spots
  • ⚠️ Sanitizer and flaky-check CI jobs for the latest head were still pending. Their completion would close the remaining CI validation gap. Available performance reports cover 9777aab3, whose changed C++ file is byte-identical to the latest head.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Oct 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4e0c5f4b0 with master bee6deac1 (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

5 object files changed (+222.97 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.34 MiB 13.55 MiB +222.97 KiB (+1.63%)

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

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

Job report

One of the 50 flaky-check runs timed out at 600 s. The flaky check runs
the server under the thread fuzzer, which makes every mutex operation and
large allocation expensive, and that run drew `index_granularity = 49`
with compact parts and sparse serialization: the INSERT alone took 48 s,
and reading the 500000-row table once decompressed ~71000 tiny blocks.
The base binary is as slow as this PR on the same settings.

Clamp `index_granularity` and `index_granularity_bytes` to their defaults
or higher, use 150000 rows, 997-row blocks instead of 97-row ones (still
not a multiple of the run lengths, and a block now ends with a partial
chunk after full ones) and 10000 rows in the overflow query.

The two-level query grouped by `x % 2`, an 8-bit key, which takes
`addBatchLookupTable8`, so its sets never reached the new loop. It now
reads one stream of 330000 rows with a `UInt32` key, 110000 keys in one
group and `max_threads = 2` (with one thread the sets never convert);
gdb shows the `UInt64` and the `String` set converting inside
`addBatchExact` while repeats are skipped.

Replaying the random settings of all 50 CI runs locally under the same
thread fuzzer settings, 8 at a time: the old test took up to 417 s (more
than 800 s for the failing run), the new one up to 126 s; results match
the reference in every run, and mutations M1-M6b still fail the test.

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

@alexey-milovidov alexey-milovidov 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.

Great idea!

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 30, 2026
Merged via the queue into ClickHouse:master with commit 0fa0b74 Oct 30, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 30, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 7, 2026
…tring or IPv6

`uniqExact` stores `sipHash128Padded` of each `String` / `FixedString` value (IPv6 as its 16
bytes) and hashed one row at a time. Now a chunk of 256 rows first chooses the rows that get a
key exactly as before (NULL, false `-If`, null place and repeated (place, value) rows are
skipped), then hashes them with one call of the vectorized functions of ClickHouse#129204, and inserts the
keys in the same order. Fewer than 8 chosen rows are hashed one at a time, as those functions
would do anyway. The hashes, and so the serialized states, do not change. Builds without AVX2 or
NEON hash one row at a time inside the same functions.

Two row-list variants are added next to ClickHouse#129204's functions: `sipHash128PaddedStringRows`
(`SipHashStrings::hashRows` over a row list) and `sipHash128PaddedFixedStringRows`.

Converted call sites, chosen by measurement (ClickHouse#129436 item 5; 1, 16 and all threads, String
0-15 / 16-64 / 0-300 bytes, FixedString(16) / (64), IPv6, 3 ABAB rounds + 5-round re-runs of
cells above 1.03), fix / master time:
- GROUP BY without consecutive repeats (the ClickHouse#128190 fallback, before: one `add` per row):
  0.37-0.66 at 1 thread, 0.57-0.91 at 16 and all threads.
- `-If` true on 50-99% of the rows and `Nullable` without GROUP BY: 0.58-0.77 at 1 thread,
  0.63-0.92 at 16 and all threads.
- `-If` true on 1-10% of the rows without GROUP BY, 1-50% with GROUP BY: 0.77-1.03.
- No key, consecutive values rarely repeat (the last-value cache off), String and FixedString:
  0.69-1.02.
- GROUP BY with repeats (ClickHouse#128190) and no key with repeats (the last-value cache): 0.80-1.06.

Left out:
- No key without repeats for IPv6: 1.098 on 20M distinct values after a 5-round re-run.
- A `UInt8` key (`addBatchLookupTable8` is `final` in the data helper), `Nullable` with GROUP
  BY and `-If` with a `UInt8` key (combinator code), `-StateIf` (the `-State` inside `-If` adds
  one row at a time), the radix `uniqExact` (separate change), variadic `uniqExact` (ClickHouse#129435).

`sip_hash_128_strings.xml` gets an `IPv6` table and these shapes, including `-If` true on 50% and
on 1% of the rows, and no key without repeats.

Related: ClickHouse#129436

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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). 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.

COUNT(DISTINCT) with GROUP BY: skip rows that repeat the previous row's group and value (ClickBench q9 −19%, q10 −16% on Graviton3)

3 participants