Skip to content

Validate skip_degree when reading a uniq aggregate state - #115276

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:validate-uniq-skip-degree-on-read
Aug 19, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:validate-uniq-skip-degree-on-read

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed silently incorrect results and undefined behavior when reading a malformed AggregateFunction(uniq, ...) state. The skip_degree field of the serialized state was used as a shift exponent without validation, so an out-of-range value produced an arbitrary cardinality instead of an error. Such states are now rejected with INCORRECT_DATA.

Description

Found by the AST fuzzer on an unrelated PR; the defect is in trunk. UndefinedBehaviorSanitizer: shift exponent 128 is too large for 64-bit type at UniquesHashSet<>::size(), STID 3207-4f9c. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107943&sha=1a89f6f2660c232730fd45bc1878d5d8443f7350&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29

skip_degree is the first byte of a serialized uniq state and read() accepted any value for it. Three sites shift by it: size() shifts a UInt64 twice and good() a UInt32, so 32 or more is undefined. Such a value can only arrive by deserializing a state, ordinary user input. The exponent wrapped modulo 64, so a release build returned a wrong answer with no error:

SELECT finalizeAggregation(CAST(unhex('8003FF6321D0F2F6B3C3E0A35D4C')
                           AS AggregateFunction(uniq, UInt64, UInt64)));
-- 3

Thinning leaves at most 2 ^ (32 - skip_degree) hashes and shrinkIfNeed() raises the degree only while more than UNIQUES_HASH_MAX_SIZE remain, so one past that budget is the last degree it can produce. read() rejects anything above it.

The same bound now holds at the other writer, as in ReservoirSamplerDeterministic.h: a buffer repeating one maximally divisible hash keeps a count thinning cannot reduce, so shrinkIfNeed() would otherwise raise the degree without limit. It has no SQL route, so it carries no separate test.

That last accepted degree still admits a count which saturates the hash space, where the systematic-error correction underflows its subtraction and casts a negative double to size_t. write() serializes such a state, so rejecting it would refuse ClickHouse's own output; size() saturates the count instead.

UNIQUES_HASH_MAX_SIZE_DEGREE has been 17 for this file's whole history, so no released version could write a rejected degree. No format change, no new setting.

Not addressed here: the file's three pre-existing Poco::Exception throws surface as the opaque Code: 1001, and reinsertImpl() does not dedupe.


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

Version info

  • Merged into: 26.8.1.1680 (included in 26.8 and later)
  • Backported to: 26.7.7.21, 26.6.5.33, 26.3.30.5

skip_degree is the first byte of a serialized AggregateFunction(uniq, ...)
state and read() accepted any value for it. Three sites shift by it:
size() shifts a UInt64 twice, and good() shifts a UInt32, so a degree of
32 or more is undefined behaviour. UBSan reported the 64-bit shift from
the AST fuzzer; on x86 the exponent is taken modulo 64, so a state
declaring degree 128 silently returned the cardinality of degree 0
instead.

Thinning leaves at most 2 ^ (32 - skip_degree) hashes and shrinkIfNeed()
raises the degree only while more than UNIQUES_HASH_MAX_SIZE of them
remain, so the last degree it can produce is one past the thinning
budget. Both writers of the field are now bounded by that maximum.
read() rejects a larger value off the wire with INCORRECT_DATA.
shrinkIfNeed() throws rather than incrementing past it, which is needed
because reinsertImpl() does not dedupe: a deserialized buffer repeating
one maximally divisible hash keeps a count that thinning cannot reduce,
so the loop would otherwise raise the degree without limit and reach the
undefined shift in good(). ReservoirSamplerDeterministic bounds both of
its writers the same way, by rejection in read() and by a throw in
setSkipDegree().

The last accepted degree still admits a count that saturates the hash
space: at degree 16 with 65536 hashes the thinned count reaches 2 ^ 32,
so the systematic-error correction subtracts it from 2 ^ 32, underflows
the difference, and casts a negative double to size_t. Since write()
serializes that state, rejecting it on read would refuse input
ClickHouse itself produced, so size() saturates the count instead and
reports the largest value the correction can express.

Every state a released version could write is still accepted:
UNIQUES_HASH_MAX_SIZE_DEGREE has been 17 for the file's whole history,
so no writer could emit a larger degree, and size() is now defined for
every state that passes the check. No format change and no new setting.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107943&sha=1a89f6f2660c232730fd45bc1878d5d8443f7350&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
ClickHouse#107943
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Reviewed cold by an independent model before publication (six rounds; earlier rounds found and
fixed three blockers: an off-by-one that would have rejected legitimate skip_degree=16 states, a
payload route that bypassed the header check, and undefined behavior at the terminal state). This
round: no blocker, no major.

# Finding Verdict
💡 The crafted merge() payloads are quadratic: 65536 copies of 0x80000000 all probe from one slot, and 1..65536 occupy 3 buckets. Use hashes spread across place() buckets instead. Disagree. The arithmetic is right (~2.1e9 and ~1.1e9 probe steps), but the clustering is forced by the invariant under test, not a payload choice. Reaching the shrinkIfNeed() ceiling needs more than UNIQUES_HASH_MAX_SIZE entries that degree-16 thinning cannot drop, i.e. every one a multiple of 2^16; there are exactly 65535 such nonzero UInt32 values, plus has_zero = 65536, which is not more than 65536. Any buffer that survives that thinning is a set of multiples of a large power of two, which place() maps to few slots. Measured cost: 3.7s for four tests in a debug build.
💡 Three pinned expected values depend on intHashCRC32, which falls back to intHash64 on targets without hardware CRC32 (248355 would be 252117 there). Disagree. Not reachable: every job that runs tests requires an amd_* (x86-64-v2, so SSE4.2) or arm_* (armv8+crc) artifact; amd_compat, riscv64 and loongarch64 are built but no test job requires them. Also precedented: 03821_uniq_speedup_boundaries.sql already pins 100315 for uniq over numbers(100000), which is arch-variant in the same way.
💡 The canonical gtest arm stops one element short of the count that makes size() saturate, so no arm shows the saturation is reachable without crafted bytes. Disagree. Provenance only. The line is pinned by the last SQL arm, which is the sole arm that reaches it; reverting the clamp flips exactly that arm. Extending the canonical arm would change what it asserts (it pins the bound at 16, reddening if tightened to 15) without covering another line.

Also noticed, not raised: this file's three pre-existing Poco::Exception throws surface as the
opaque Code: 1001, and reinsertImpl() does not dedupe. Both are pre-existing and noted in the
description; #111493 is already rewriting that function.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 18, 2026
/// These arms use only the public API, so `skip_degree` is recovered from the first byte of the
/// serialized form.

#include <AggregateFunctions/UniquesHashSet.h>

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.

@groeneai remove the gtest when there is a sql test

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in 9de81a4.

I checked whether the SQL arms cover the same thing before deleting, and they do not quite: the gtest was the only arm reaching the shrinkIfNeed() ceiling. That path turns out to be unreachable from SQL, so I removed the test rather than replace it. Reaching the throw needs an element count thinning cannot reduce, sitting in a merge destination. read() can build such a state because reinsertImpl() does not deduplicate, but every SQL merge destination is created by insertDefault(), and insertFrom(place) is insertDefault(); insertMergeFrom(place), so a crafted state is only ever the merge source, where insertImpl() does deduplicate. Five routes, none reaching it: uniqState + uniqState, arrayReduce('uniqMergeState'), runningAccumulate, uniqMerge over repeated rows, and uniqMerge over the saturating degree-16 payload.

So that guard is now untested, and by your criterion it is also unreachable, which makes it defensive code. I have kept it because it bounds the field at both writers, but I am equally happy to drop it and keep only the read() bound and the size() clamp, which are what fix the reported UBSan and are covered by the arms in 02477_invalid_reads. Say which you prefer.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I would keep the guard and leave the gtest removed.

After tracing ColumnAggregateFunction::deserialize, insertFrom, and insertMergeFrom, I agree with your conclusion that SQL-visible merges only ever see a crafted uniq state as the merge source, not the destination. In that shape the read-side bound and the size() clamp are the reachable fix, while the shrinkIfNeed() check is still a reasonable defensive invariant on the in-memory writer side.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9de81a4]

Summary: ✅


AI Review

Summary

This PR validates skip_degree when deserializing uniq aggregate states, clamps the terminal saturated case in size(), and adds focused stateless coverage for the reachable read-side behavior. I did not find any new correctness, safety, performance, or PR-metadata issues in the current revision.

Missing context / blind spots
  • ⚠️ Most full CI jobs are still pending, so this review could only rely on code inspection plus the completed Fast test, Style check, and build-profile checks. The remaining amd_* and arm_* jobs would close the last runtime and portability gap.
Final Verdict

✅ No new findings in the current revision.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 18/21 (85.71%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SELECT finalizeAggregation(CAST(unhex('8003FF6321D0F2F6B3C3E0A35D4C') AS AggregateFunction(uniq, UInt64, UInt64)))". 0x80 is 128, the exponent in the CI report. Fires on demand, no randomization.
b Root cause explained? Yes. skip_degree is the first byte of a serialized uniq state and read() accepted any value for it. Three sites shift by it: size() shifts a UInt64 twice and good() shifts a UInt32. In-process growth cannot reach a bad value, so it can only arrive by deserializing an untrusted state. A second, non-shift site is reached even by in-range degrees: at the terminal degree the thinned count can saturate the hash space, underflowing the correction term's subtraction.
c Fix matches root cause? Yes. The degree is validated in read(), where the untrusted input enters, rather than clamped at each shift site. The saturation case is different in kind: write() serializes that state, so it is valid input and is handled where the formula breaks down, in size(), instead of being rejected on read.
d Test intent preserved / new tests added? Yes, and every enforcement point now has committed coverage. Five arms appended to the existing 02477_invalid_reads.sql, the canonical home for aggregate-state deserialization checks: no pre-existing arm was modified, pure SQL, no tables or files, so no no-parallel tag; the accepted arms carry hashes that are genuine multiples of 2 ^ skip_degree, so their expected values depend on the payload. The shrinkIfNeed() throw has no SQL route (every insertMergeFrom destination is freshly constructed, and runningAccumulate merges the deserialized state in as the source), so it is covered by src/AggregateFunctions/tests/gtest_uniques_hash_set_skip_degree.cpp: one positive arm plus three controls, using only the public API.
e Both directions demonstrated? Yes. Running 02477_invalid_reads against the base binary FAILS on all three serverError arms and prints the wrong values 18446743978444128520, 3, 510522 and 18446743978444128518; the fixed binary passes in 0.84s. Corrupting either accepted arm's expected value by one digit also FAILS, so both oracles are live. A mutation table was recorded over all three enforcement points: reverting the read-side ceiling flips SQL arms 1 to 3, reverting the size() saturation flips SQL arm 5, and reverting the shrinkIfNeed() throw makes the gtest positive arm hang (exit 124 under timeout 60) while its three controls stay green. Tightening the bound by one reddens the canonical-set control with Cannot thin out UniquesHashSet: 65537 elements remain at the maximum skip degree of 15, so that green result is a live oracle rather than a vacuous one. No arm survives its own reversion; the deliberate over-reach control at degree 16 is unchanged in every mutant.
f Fix is general across code paths? Yes. Entry paths verified base vs fix, each with a fresh server path: finalizeAggregation (single-arg and variadic), uniqMerge, and an AggregateFunction column round-trip through a Memory table. All four writers of skip_degree were enumerated and both that can create a value are now bounded by the same maximum: read() rejects an out-of-range byte off the wire, and shrinkIfNeed(), the only site that increases the field, throws rather than incrementing past it. The other two (operator=, merge()) only propagate an already-bounded value. The shrinkIfNeed() guard is needed because reinsertImpl() does not dedupe, so a deserialized buffer repeating one maximally divisible hash keeps a count thinning cannot reduce; without it the loop raises the degree without limit. It cannot fire for a canonical set: measured, a distinct-hash buffer reaches degree 16 and stops. Sibling uniq* variants checked at source: only AggregateFunctionUniqUniquesHashSetData{,ForVariadic} use UniquesHashSet.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified for UInt64, String, variadic UInt64, UInt64, Nullable(UInt64), LowCardinality(String) and LowCardinality(Nullable(String)), using each type's real state layout recovered by round-tripping a genuine state rather than a guessed prefix (Nullable puts the degree at offset 1). All accept at degree 15 and 16 and reject at 17, 32 and 128. All 256 values of the byte were swept base vs fix: 0 to 16 byte-identical (0 differences), 17 to 255 all rejected (239/239, no other error code). The full 2 ^ 32 cross-product of accepted degree and size was enumerated: exactly one pair saturates, and it is now defined rather than rejected.
h Backward compatible? (maintainer-approved exception only) Yes, no break. The ceiling is the terminal degree the write path can reach: thinning leaves at most 2 ^ (32 - skip_degree) hashes, so past UNIQUES_HASH_BITS_FOR_SKIP + 1 the shrinkIfNeed() condition can no longer be met. UNIQUES_HASH_MAX_SIZE_DEGREE has been 17 for this file's whole history, so no released writer could emit a larger degree, and after the size() change nothing writer-valid is rejected at all. Measured: the engine emits degree 12 at 2e8 rows against a limit of 16. No SettingsChangesHistory.cpp entry, no format change and no new setting.
i Invariants and contracts preserved? Yes, and the field's invariant now holds globally: skip_degree <= UNIQUES_HASH_BITS_FOR_SKIP + 1 at every instant, because both writers that can create a value enforce it. The read-side check runs before free() and alloc(), so it cannot leave a partially reinitialized set; has_zero is already reset above it, and its position and throw-on-invalid behavior match the pre-existing m_size guard in the same function. The shrinkIfNeed() throw is placed before the increment, so the bound is never transiently exceeded. Exception safety was checked on both paths: nothing in this file or AggregateFunctionUniq.h is noexcept, and all four shrinkIfNeed() call sites are reached from ordinary throwing aggregate paths. size() stays total: the saturation branch keeps the argument of log() positive on every path, and the reported value is monotone against its neighbour (95265423098 at the saturated count against 48882212795 one below).

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @alexey-milovidov, could you review this? skip_degree is the first byte of a serialized uniq state and read() accepted any value for it, so it reached three shift sites unvalidated: a release build returned an arbitrary cardinality with no error, and UBSan reported shift exponent 128 is too large. Both writers that can create the value now enforce the same bound, and the second one has no SQL route, so it is covered by a unit test rather than a stateless test.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9de81a4c7 with master 48e35ab80 (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
Binary Master PR Δ
programs/clickhouse-stripped 702.05 MiB 699.01 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

5 object files changed (-85.34 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 10.67 MiB 10.59 MiB -85.33 KiB (-0.78%)

737 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

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

Job report

The gtest only covered the shrinkIfNeed() ceiling. Reaching that throw needs a
state whose element count thinning cannot reduce, in a merge destination
position. read() builds such a state through reinsertImpl(), which does not
dedupe, but every SQL merge destination is created by insertDefault(), and
insertFrom(place) is insertDefault() followed by insertMergeFrom(place). A
crafted state can therefore only ever be the merge source, where insertImpl()
does dedupe.

Measured on five routes, none of which reaches the throw: uniqState + uniqState,
arrayReduce('uniqMergeState'), runningAccumulate, uniqMerge over repeated rows,
and uniqMerge over the saturating degree-16 payload.

The read() bound and the size() clamp are what fix the reported UBSan, and both
are covered by the arms in 02477_invalid_reads.
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Aug 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 19, 2026
Merged via the queue into ClickHouse:master with commit ad71fec Aug 19, 2026
183 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
alexey-milovidov added a commit that referenced this pull request Aug 20, 2026
Master brought the skip_degree validation of #115276 (kept, and the same bound
style is applied to the wide set) and took protocol revision 54492 for the String
size stream, so DBMS_MIN_REVISION_WITH_UNIQ_STATE_VERSION_1 moves to 54493.

Co-Authored-By: Claude Fable 5 <[email protected]>
@nikitamikhaylov nikitamikhaylov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 2, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 2, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 2, 2026
Backport #115276 to 26.6: Validate skip_degree when reading a uniq aggregate state
alexey-milovidov added a commit that referenced this pull request Sep 3, 2026
Backport #115276 to 26.3: Validate skip_degree when reading a uniq aggregate state
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
nikitamikhaylov added a commit that referenced this pull request Sep 4, 2026
Backport #115276 to 26.7: Validate skip_degree when reading a uniq aggregate state
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
AGG: malformed uniq state (skip_degree) -> wrong/UB.
Effect in the production build a394e92: its upstream test(s) 02477_invalid_reads fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 02477_invalid_reads.

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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

7 participants