Repository navigation
Avoid overflow in the uniq aggregate function at cardinalities above ten billion - #115393
Conversation
A view of a `ColumnAggregateFunction` (the result of a filter, a permutation - e.g. a sort -
or an index operation) and a plain copy of it dropped the state `version` and the type string.
The version affects how the states are serialized: `groupArray` over a state column serializes
the states into its own state and deserializes them back at the version of the result column,
so a query like
SELECT arraySlice(groupArray(x), 1, 1)
FROM (SELECT medianDeterministicState(number, number) AS x FROM numbers(10) GROUP BY number ORDER BY number)
failed with an exception (`Cannot read all data` / `Extra bytes found after deserializing aggregation state`)
for any versioned aggregate function state: the states collected from the sorted (view) column were
serialized at version 0, while the result column deserialized them at version 1.
The test is added in the last commit of this pull request, together with the version 1
of the `uniq` state (the reference values depend on it).
Co-Authored-By: Claude Fable 5 <[email protected]>
…ck marshalling
`ColumnBLOB::toBLOB` serialized the column with the state version resolved from the local type,
while `NativeWriter::write` announces the type with the version derived from the negotiated
revision. For a versioned aggregate function state (e.g. `quantileDeterministic`) the payload
of a marshalled block was thus written at version 0 while the announced type said version 1,
and the receiver lost sync inside the blob, e.g.:
SELECT medianDeterministic(n, n) FROM remote('127.0.0.{1,2}', default, t) GROUP BY n % 2
SETTINGS enable_parallel_blocks_marshalling = 1, prefer_localhost_replica = 0
failed with an exception (`Skip degree in quantileDeterministic state is 120, which exceeds the maximum value of 31`).
Derive the version in `toBLOB` exactly the same way `NativeWriter::write` does.
The test is added in the last commit of this pull request, together with the version 1
of the `uniq` state (the reference values depend on it).
Co-Authored-By: Claude Fable 5 <[email protected]>
…ten billion The `uniq` state kept only 32 bits of each hash, so beyond a few billion distinct values the estimate saturated, and above ~30 billion the correction formula computed `log` of a non-positive number, and the cast of the resulting infinity to an integer was undefined behavior that produced values like 18446743978444128518. The state now keeps full 64-bit hashes (state version 1 - the versioning scheme follows the one of `quantileDeterministic`, see 42cecd2 and 3d1b631): - an unversioned type keeps the legacy byte layout, so all persisted data stays readable; - a fresh state spells version 1 out in its type, a fresh table gets it pinned at DDL time; - on the wire the version is derived from the negotiated revision, so an old peer receives the states with the hashes truncated to 32 bits - exactly the values it would have computed itself; - a state carrying only 32 bits of hash information (read from an old table or received from an old server) is kept in a compat mode, and merging a 64-bit state with it downgrades the former by truncation, because the missing bits cannot be recovered - the result matches the legacy computation bit for bit; - the legacy estimate formula is clamped, so a saturated legacy state now returns the saturation limit (about 9.5e10) instead of the garbage above. SELECT uniq(number) FROM numbers_mt(100000000000) now returns 100288510111 (+0.29%), and 1010107886346 (+1.0%) for a trillion, instead of 18446743978444128518. The cost: the stored hashes are twice as large, so a saturated state takes 1 MiB of memory and 512 KiB serialized (instead of 512 KiB / 256 KiB), and group-heavy queries with mid-sized groups are moderately slower due to the doubled memory traffic. Closes: #6078 Co-Authored-By: Claude Fable 5 <[email protected]>
# Conflicts: # docs/reference/interfaces/specs/NativeProtocol.mdx # src/AggregateFunctions/UniquesHashSet.h # src/Core/ProtocolDefines.h
|
Workflow [PR], commit [d2e857d] Summary: ✅
AI ReviewSummaryThis PR fixes the Findings
Final Verdict
LLVM Coverage ReportMeasured on commit d2e857d.
Changed lines: Changed C/C++ lines covered: 423/456 (92.76%) · Uncovered code |
|
I don't like doubling memory usage in every case. Can we make it so that it will grow up to ~1 billion and then convert (with inevitable loss of precision for already consumed data)? |
…-bit hashes #115393 (comment) Instead of storing all hashes as 64-bit values (which doubled the memory of every `uniq` state), the main sample keeps the historical 32-bit format bit for bit, so below two billion elements the estimates, the memory usage and the serialized state are exactly as before. In addition, a small sample of full 64-bit hashes is maintained (this is what state version 1 carries): only one hash in 262144 enters it and it is bounded by 16384 values (256 KiB), so it stays empty or tiny for normal states - about 4 values per million distinct elements - and the estimate switches to it at about two billion, where the 32-bit sample degrades. The variant suggested in the review - grow in 32 bits up to ~1 billion, then convert the state to 64-bit hashes accepting the loss for the consumed data - turns out not to work with parallel and distributed aggregation: every partial state stays below the threshold, so no 64-bit information is ever captured, and the merged estimate saturates around 9.5e10 regardless of the real cardinality (measured exactly that on `numbers_mt(50000000000)` with an implementation of it). The wide sample is therefore maintained from the first insertion. In the batched insertion path the candidates are detected branchlessly and inserted after the loop, keeping the hot loop free of calls: the instruction count of `SELECT uniq(number) FROM numbers(100000000)` is within 0.1% of master. Since the main sample is unchanged, all the mixed-version scenarios (verified against a real 26.7 server: raw state columns and partial aggregation states, in both directions) give exactly the value the old server computes natively, and the previously updated test references of the estimates below two billion are reverted to their master values. SELECT uniq(number) FROM numbers_mt(50000000000) returns 50090681348 (+0.18%) instead of 18446743978444128518. Co-Authored-By: Claude Fable 5 <[email protected]>
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]>
|
Both points addressed, in the last two commits: "Grow up to ~1 billion and then convert" — I implemented exactly that first, and it has a fatal flaw that only shows up under parallel or distributed aggregation: every partial state stays below the threshold (a thread or shard sees only its share of the rows), so no partial ever converts, no 64-bit information is ever captured, and the merged estimate stays capped at the 32-bit saturation limit no matter the real cardinality. Measured with that implementation: "64-bit hashes with the memory offset by other means" — this works, and it is what the PR now does. The main sample stays in the historical 32-bit format bit for bit — below two billion elements nothing changes: same estimates (all the previously-updated value references reverted to their master values), same memory, same serialized bytes, and all six mixed-version scenarios against a real 26.7 server return exactly the old server's native values. In addition, the state keeps a tiny sample of full 64-bit hashes: only one hash in 262144 enters it and it is capped at 16384 values (256 KiB), so it is empty for almost every state (~4 values per million distinct elements — the memory "offset" is that it is pre-thinned out this aggressively) and the estimate switches to it at about two billion, where the 32-bit sample degrades. The wide sample has to be fed from the first insertion (that is the part that genuinely cannot be recovered later), which costs one branchless check per value; in the batched insertion path the candidates are collected outside the hot loop, and the instruction count of Memory: unchanged below ~1M distinct per state (plus one pointer in |
`02429_combinators_in_array_reduce` and `02430_initialize_aggregation_with_combinators` print raw `uniq` state bytes produced by `arrayReduce` and `initializeAggregation`, which create a fresh state type and therefore pin state version `1`. Version `1` prepends a flags byte, so both references needed the same update the other raw-state references already got. Also renumber `05023_uniq_state_version_64bit_hashes` to `05027_...`: a test with the same number, `05023_set_index_expression_widened_operand`, landed on `master` in the meantime.
Build profile diff (arm_release)Commit See the job log for details. |
A state serialized in the legacy format (state version `0`) carries no wide set of 64-bit hashes, and its elements were never offered to one. Merging such a state added all of its elements to the 32-bit main sample while leaving the wide sample untouched, so as soon as the version-1 side alone crossed the switch threshold, `size` reported the wide estimate and the legacy half of the merged state was lost entirely - a rolling upgrade merging two disjoint halves of three billion values each would report three billion instead of six. Mark such a state as having an incomplete wide sample: it drops its own wide set, never starts a new one, and propagates the mark through merges and through serialization (bit 1 of the flags byte of state version `1`), so that `size` of anything it is merged into falls back to the 32-bit estimator. The degrading precision of the 32-bit estimate is much better than silently losing a part of the elements.
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
# Conflicts: # docs/reference/interfaces/specs/NativeFormat.mdx
Once `wide_incomplete` is set, merging a clean version-1 state whose wide set had a larger `skip_degree` used to allocate an empty wide set that `wideInsert` could never fill, so the state serialized with both flag bits set - a combination the format defines as mutually exclusive. Skip the whole `rhs.wide` path for an incomplete state, reject `flags == 3` in `read` and `skip` defensively, and say so in both format specifications. Addresses the AI review of #115393
A query that replays formatted metadata - a `Replicated` database DDL log entry (including the initiator's own re-execution of the entry it wrote), an `ON CLUSTER` secondary, or a restore from a backup - already spells any pinned state version out in the type name, because the initiator normalized it. An unversioned `AggregateFunction(uniq, ...)` in such a query denotes the layout from before the function became versioned, so pinning the current version there re-created old columns as version 1 and made the version-0 data unreadable under `Replicated` databases. Pin the current version only for a definition the user wrote, and pin the empty version to 0 otherwise, the same way `ATTACH` does. Verified with a two-server `Replicated` database: the unversioned column keeps version 0 on both replicas and both read each other's parts, while a fresh column spells version 1 out everywhere. The `no-replicated-database` tag on the test is not needed anymore. Addresses the AI review of #115393
A fresh `uniq` state serializes as version 1 (with a flags byte), so the state hashes in `02751_ip_types_aggregate_functions_states` changed, and `test_backward_compatibility/test_functions.py::test_aggregate_states` now allows `uniq` states to differ between the releases as long as the new server still reads the old state to the same value. CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115393&sha=a9e15f7b5f5e559094b039bfd64c2ceb3bc8a249&name_0=PR
Suppress `cppcoreguidelines-pro-type-member-init` at the implicit constructor of `WideCandidates` (the diagnostic is reported at the struct, not at the member), and remove an extra empty line in `NativeReader.cpp`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n master The merged master replaced `IDataType::forEachChild` with `getChild` / `forEachInTypeTree` (the walk visits the root itself), which broke the build of `getAggregateStateVersions`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Fixed the two red checks of 631a00f and merged
|
…hChild Master removed `IDataType::forEachChild` (ClickHouse#115393). Its callers now walk a type with `forEachInTypeTree` / `anyInTypeTree` over `getChild`, which is implemented by the same seven types (Array, LowCardinality, Map, Nullable, Object, Tuple, Variant), so the set of reachable nested types is unchanged. `collectExpressionIdentity` and `carriesAReachableTimeZone` move to those walks. The visiting order differs only for `Map` (pre-order instead of key and value first), which is harmless: both sides of the comparison are `equals`-equal and walked the same way, and the digest is never persisted. The conflict in `DataTypeObject.cpp` is resolved by taking master's side: master replaced `forEachChild` there with `getChild` over the new `sorted_typed_paths`, which already gives the canonical path order this branch's sorted `forEachChild` provided. The `paths_to_skip` sort in `updateHashImpl` is kept, master still hashes that set unsorted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hSet::merge` After merging master, the wide-set merge loop added by ClickHouse#115393 declares its own `i`, which shadows the batch index and fails the build with `-Wshadow`. This removed the PR from the merge queue: https://github.com/ClickHouse/ClickHouse/actions/runs/37976827113 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`extractGroups` passed `NumberOfCapturingGroups() + 1` submatch slots to `RE2::Match` with no bound of its own, inheriting only the shared `MAX_SUBPATTERNS = 1024` ceiling. Its siblings `extractAllGroupsHorizontal` and `extractAllGroupsVertical` have rejected more than 127 capturing groups since they were added. More than five captures rules out `SearchOnePass`, so a 1024-capture pattern reaches `SearchNFA`, where `ncapture_` is `2 * nsubmatch` and `CopyCapture` memmoves 16 KiB per NFA thread added per input position. A query using a 1023-group pattern ran for 641 seconds after cancellation had already been requested. Apply the same 127-group bound, so this function matches its siblings. Related: ClickHouse#112203 Related: ClickHouse#115393 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115393&sha=704edd9a1ea45f98fc18d0aafe1754ce63b1314d&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
A `remote()`/`Distributed` shard that applies `ARRAY JOIN` (or a `JOIN`) with `enable_lazy_columns_replication = 1` (the default) sends the non-joined columns as `ColumnReplicated`, and the initiator's `NativeReader` reconstructs them as such. When an `AggregateFunction` column arrives with a state version different from the header's (e.g. a table pinned to `AggregateFunction(0, uniq, UInt64)` while the wire carries version 1), `castColumn` calls `relabelAggregateStateVersions`, which only unwrapped `ColumnConst` and sparse columns. `recursiveRemoveSparse` keeps a top-level `ColumnReplicated`, so `ColumnAggregateFunction::insertRangeFrom` got a `ColumnReplicated` source: a `Bad cast` logical error in debug and sanitizer builds, and a segmentation fault in `UniquesHashSet::merge` on the 26.10 release build. Unwrap `ColumnReplicated` the same way as `ColumnConst`: relabel the nested column and re-wrap it with the same indexes, as `recursiveRemoveSparse` and `recursiveRemoveLowCardinality` do. The lazy representation is preserved, matching what the equal-version path returns. The relabel in `castColumn` was introduced in ClickHouse#115393. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The bugs behind their `no-parallel-replicas` / `no-replicated-database` tags are fixed on master: - `01660_join_or_any`: ClickHouse#123683 - `04653_bloom_filter_fixed_string_constant_scalar`: ClickHouse#118988 - `04819_dynamic_aggregate_function_state_version`: ClickHouse#123649 - `04825_quantile_deterministic_alter_add_modify_column`: ClickHouse#115393, ClickHouse#123070 - `04494_atomic_populate_materialized_view_parallel_replicas`: ClickHouse#124477 - `04266_text_index_tokens_cardinality_order`: ClickHouse#124500 already disables parallel replicas for the log-checked query Related: ClickHouse#124015
Closes: #6078
Related: #112052
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
uniqaggregate function returned garbage (e.g.18446743978444128518) for cardinalities above roughly thirty billion, because its state kept only 32 bits of each hash and the correction formula overflowed. The state now additionally keeps a small sample of full 64-bit hashes (state version1) which the estimate switches to at about two billion elements:SELECT uniq(number) FROM numbers_mt(100000000000)returns99360630405(−0.64%), and the estimate stays accurate (about 1%) up to trillions. Below two billion nothing changes: the estimates, the memory usage and the state format are exactly as before, and states written by older versions remain readable and merge correctly in mixed-version clusters.The bug
The
uniqstate (UniquesHashSet, a BJKST-style adaptive sampling set) keeps hashes truncated to 32 bits. Beyond a few billion distinct values all2^32hash values fill up, and the collision-correction formula computesround(2^32 * (log(2^32) - log(2^32 - res)))withres >= 2^32—logof a non-positive number, and the cast of the resulting infinity/NaN to an integer is undefined behavior that produced the values reported in the issue.The fix
The main sample stays in the historical 32-bit format, bit for bit — below two billion elements nothing changes at all: same estimates, same memory, same serialized bytes. In addition, the state maintains a small sample of full 64-bit hashes (the "wide" set): only one hash in
262144enters it, and it is bounded by 16384 values (256 KiB), thinned out further beyond that. For normal states it is empty or tiny — about 4 values per million distinct elements — andsize()switches to it once it has at least 8192 values, i.e. at about two billion elements, where its statistical error (~1%) meets the degrading precision of the 32-bit sample. The legacy formula is also clamped, so a saturated 32-bit estimate returns its saturation limit (~9.5e10) instead of the garbage above.The wide sample must be fed from the very first insertion — the high bits of the hashes of already-consumed elements are unrecoverable. This also rules out the reviewer-suggested variant of converting the state at a threshold: with parallel or distributed aggregation every partial state stays below any threshold, no 64-bit information is ever captured, and the merged estimate stays capped (~9.5e10) no matter the real cardinality — I implemented that variant and measured exactly this on
numbers_mt(50000000000). Feeding a heavily pre-thinned sample from the start gets the same memory profile without that trap.State versioning follows the
quantileDeterministicscheme (#112052) exactly: version1(a flags byte, the main sample in the legacy layout, then the wide sample if present) is spelled out in fresh state types and pinned at DDL time; the default version stays0so unversioned persisted data keeps its layout; the wire version is derived from the negotiated revision (new constantDBMS_MIN_REVISION_WITH_UNIQ_STATE_VERSION_1 = 54493), so an old peer receives plain version-0states. A version-0state simply carries no wide sample, and merging it degrades only the merged-in elements to the old 32-bit precision.Results
Cross-version compatibility was verified against a real 26.7 server: all six mixed-version scenarios (raw state columns and partial aggregation states, both directions, plus a two-shard mixed
remote) return exactly the value the old server computes natively (1001943fornumbers(1000000)), since the main sample is identical.Costs
sizeofof the state grows by one pointer). From there the wide sample addsn / 16384bytes, up to +50% (256 KiB over the 512 KiB main table) for multi-billion-cardinality states.good()test of the main set, collects them into a local buffer, and keeps the batch loop fully unrolled. The wide sample takes the full hashes XOR-ed with a constant (wideHash), so the hash of the integer0(which is0) is never a candidate - otherwise a column dominated by zeros made every row a candidate. A microbenchmark ofinsertManyagainst master with the same build flags: distinct numbers +2%, a zero-dominated column 0%, a million distinct values +2%, a tiny set of non-zero duplicates +15%.Two latent bugs of #112052 fixed on the way
Both reproduce with
quantileDeterministicon current master and were exposed by the newuniqversion:ColumnBLOB::toBLOB(parallel block marshalling) serialized the payload with the state version resolved from the local type, whileNativeWriter::writeannounces the version derived from the negotiated revision, so the receiver lost sync inside the blob:SELECT medianDeterministic(n, n) FROM remote('127.0.0.{1,2}', default, t) GROUP BY n % 2 SETTINGS enable_parallel_blocks_marshalling = 1, prefer_localhost_replica = 0failed withSkip degree in quantileDeterministic state is 120(an exception, in a release build).ColumnAggregateFunction(the result of a sort, filter, or index operation) and a plain copy of it dropped the state version, soSELECT arraySlice(groupArray(x), 1, 1) FROM (SELECT medianDeterministicState(number, number) AS x FROM numbers(10) GROUP BY number ORDER BY number)failed withCannot read all data.Tests
test_backward_compatibility/test_block_marshalling.py::test_old_replica_state_under_versioned_header: a version0state from an old shard read under aAggregateFunction(1, uniq, UInt64)header must take the version of the header (castColumnignored the version, becauseIDataType::equalsdoes).A
gtestsuite forUniquesHashSet: the estimator at a simulated cardinality of10^11, the saturation clamp of the legacy formula, round trips of both formats, wide-sample merges with thinning, merges with legacy states, the insertion path feeding the wide sample, and rejection of corrupt states.05023_uniq_state_version_64bit_hashes: version pinning, wire round trips of both versions, cross-version merges, and that the values below two billion are identical across versions.05024_aggregate_state_version_parallel_marshalling,05025_aggregate_state_version_in_column_viewsfor the two bugs above (covering bothuniqandquantileDeterministic).05026_uniq_64bit_sample_above_two_billion(long): an end-to-end four-billion-row check of the switch to the 64-bit sample; the result does not depend on the distribution of rows between threads.Since the 32-bit sample is bit-identical to master, only the tests that print state type names or raw state bytes needed reference updates; all
uniqvalue references below two billion are untouched.Workflow [PR]
Sync PR [sync-upstream/pr/115393]
Version info
26.10.1.1608-master(included in26.10and later)