Repository navigation
Validate skip_degree when reading a uniq aggregate state - #115276
alexey-milovidov merged 2 commits into
Conversation
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
Internal second-model review (click to expand)Reviewed cold by an independent model before publication (six rounds; earlier rounds found and
Also noticed, not raised: this file's three pre-existing |
| /// These arms use only the public API, so `skip_degree` is recovered from the first byte of the | ||
| /// serialized form. | ||
|
|
||
| #include <AggregateFunctions/UniquesHashSet.h> |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Workflow [PR], commit [9de81a4] Summary: ✅
AI ReviewSummaryThis PR validates Missing context / blind spots
Final Verdict✅ No new findings in the current revision. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 18/21 (85.71%) · Uncovered code |
Pre-PR validation gate (click to expand)
|
|
cc @rschu1ze @alexey-milovidov, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes5 object files changed (-85.34 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units9 translation units recompiled, 41 s compile time in total, 9 of them have a recent master baseline. |
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.
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]>
Backport #115276 to 26.6: Validate skip_degree when reading a uniq aggregate state
Backport #115276 to 26.3: Validate skip_degree when reading a uniq aggregate state
… a uniq aggregate state
… a uniq aggregate state
Backport #115276 to 26.7: Validate skip_degree when reading a uniq aggregate state
… a uniq aggregate state
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]>
Changelog category (leave one):
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. Theskip_degreefield 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 withINCORRECT_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 typeatUniquesHashSet<>::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%29skip_degreeis the first byte of a serializeduniqstate andread()accepted any value for it. Three sites shift by it:size()shifts aUInt64twice andgood()aUInt32, 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:Thinning leaves at most
2 ^ (32 - skip_degree)hashes andshrinkIfNeed()raises the degree only while more thanUNIQUES_HASH_MAX_SIZEremain, 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, soshrinkIfNeed()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_DEGREEhas 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::Exceptionthrows surface as the opaqueCode: 1001, andreinsertImpl()does not dedupe.Workflow [PR]
Sync PR [sync-upstream/pr/115276]
Version info
26.8.1.1680(included in26.8and later)26.7.7.21,26.6.5.33,26.3.30.5