Skip to content

Avoid overflow in the uniq aggregate function at cardinalities above ten billion - #115393

Merged
alexey-milovidov merged 41 commits into
masterfrom
uniq-64bit
Oct 5, 2026
Merged

alexey-milovidov merged 41 commits into
masterfrom
uniq-64bit

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Closes: #6078
Related: #112052

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):

The uniq aggregate 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 version 1) which the estimate switches to at about two billion elements: SELECT uniq(number) FROM numbers_mt(100000000000) returns 99360630405 (−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 uniq state (UniquesHashSet, a BJKST-style adaptive sampling set) keeps hashes truncated to 32 bits. Beyond a few billion distinct values all 2^32 hash values fill up, and the collision-correction formula computes round(2^32 * (log(2^32) - log(2^32 - res))) with res >= 2^32 — log of 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 262144 enters 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 — and size() 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 quantileDeterministic scheme (#112052) exactly: version 1 (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 stays 0 so unversioned persisted data keeps its layout; the wire version is derived from the negotiated revision (new constant DBMS_MIN_REVISION_WITH_UNIQ_STATE_VERSION_1 = 54493), so an old peer receives plain version-0 states. A version-0 state simply carries no wide sample, and merging it degrades only the merged-in elements to the old 32-bit precision.

Results

SELECT uniq(number) FROM numbers_mt(2000000000)     -- 2006192184    (+0.31%, still the 32-bit sample)
SELECT uniq(number) FROM numbers_mt(4000000000)     -- 4028331215    (+0.71%, the 64-bit sample)
SELECT uniq(number) FROM numbers_mt(50000000000)    -- 50267749176   (+0.54%), was 18446743978444128518
SELECT uniq(number) FROM numbers_mt(100000000000)   -- 99360630405   (-0.64%), was 18446743978444128518
SELECT uniq(number) FROM numbers_mt(1000000000000)  -- 1003779179926 (+0.38%)

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 (1001943 for numbers(1000000)), since the main sample is identical.

Costs

  • Memory and serialized size are unchanged below ~1 million distinct elements per state (the wide sample is empty for almost all states; sizeof of the state grows by one pointer). From there the wide sample adds n / 16384 bytes, up to +50% (256 KiB over the 512 KiB main table) for multi-billion-cardinality states.
  • The insertion hot path checks the candidates for the wide sample only behind the 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 integer 0 (which is 0) is never a candidate - otherwise a column dominated by zeros made every row a candidate. A microbenchmark of insertMany against 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%.
  • Above two billion the estimate error is ~0.8-1.1% (8192-16384 samples) versus ~0.6% below — and versus garbage before this change.

Two latent bugs of #112052 fixed on the way

Both reproduce with quantileDeterministic on current master and were exposed by the new uniq version:

  • ColumnBLOB::toBLOB (parallel block marshalling) serialized the payload with the state version resolved from the local type, while NativeWriter::write announces 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 = 0 failed with Skip degree in quantileDeterministic state is 120 (an exception, in a release build).
  • A view of a ColumnAggregateFunction (the result of a sort, filter, or index operation) and a plain copy of it dropped the state version, so SELECT arraySlice(groupArray(x), 1, 1) FROM (SELECT medianDeterministicState(number, number) AS x FROM numbers(10) GROUP BY number ORDER BY number) failed with Cannot read all data.

Tests

  • test_backward_compatibility/test_block_marshalling.py::test_old_replica_state_under_versioned_header: a version 0 state from an old shard read under a AggregateFunction(1, uniq, UInt64) header must take the version of the header (castColumn ignored the version, because IDataType::equals does).

  • A gtest suite for UniquesHashSet: the estimator at a simulated cardinality of 10^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_views for the two bugs above (covering both uniq and quantileDeterministic).

  • 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 uniq value references below two billion are untouched.


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

Version info

  • Merged into: 26.10.1.1608-master (included in 26.10 and later)

alexey-milovidov and others added 4 commits August 19, 2026 05:00
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
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d2e857d]

Summary: ✅


AI Review

Summary

This PR fixes the uniq overflow at very large cardinalities by adding a versioned 64-bit side sample and then threading aggregate-state versions through Native, combinators, casts, and DDL pinning. The core serialization and cast fixes look solid, but I do not think the rollout contract is complete yet: the legacy unnormalized ON CLUSTER DDL path still skips initiator-side pinning for versioned aggregate states, so the same CREATE can silently downgrade explicit AggregateFunction(...) columns to version 0 and can even infer different schemas across mixed-version hosts for CREATE ... AS SELECT ...State(...). Because that compatibility path remains live, I would still request changes.

Findings
  • ⚠️ Majors
    • [src/Interpreters/InterpreterCreateQuery.cpp:703] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/115393#discussion_r4036750139] The new invariant is “every path that persists or fans out an aggregate-state type must either pin the initiator’s chosen version or fail closed.” The old distributed_ddl_entry_format_version < NORMALIZE_CREATE_ON_INITIATOR_VERSION path still violates that invariant in two ways: getColumnsDescription treats every DDL worker as “already normalized” and therefore skips pinCurrentStateVersionToAggregateFunctions for explicit AggregateFunction(...) columns, while the CREATE ... AS SELECT inference path still pins ...State(...) types locally at src/Interpreters/InterpreterCreateQuery.cpp:1187. In a mixed-version rollout, the same unnormalized ON CLUSTER query can therefore create version-0 explicit columns everywhere, or worse, infer version-1 columns on new hosts and legacy columns on old hosts. Suggested fix: extend the initiator-side rewrite in prepareOnClusterQuery at src/Interpreters/InterpreterCreateQuery.cpp:3645 to pin versioned aggregate-state types for this legacy DDL format too, or reject CREATE statements that mention or infer versioned aggregate states when the entry format is too old; add a focused regression for distributed_ddl_entry_format_version = 2 with CREATE ... AS SELECT uniqState(...).
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Pin or reject versioned aggregate-state types on the legacy unnormalized ON CLUSTER DDL path instead of silently downgrading or diverging.
    • Add a regression that exercises distributed_ddl_entry_format_version < 3 with versioned AggregateFunction columns or ...State(...) inference.

LLVM Coverage Report

Measured on commit d2e857d.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.20% 91.80% -0.40%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 423/456 (92.76%) · 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 19, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft August 19, 2026 17:05
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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)?

alexey-milovidov and others added 2 commits August 20, 2026 03:04
…-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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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: SELECT uniq(number) FROM numbers_mt(50000000000) returned 95265432934 — the saturation constant, not 50 billion. So it is not "absolutely impossible", but the loss is not the bounded one we hoped for: it silently reverts to a 32-bit answer exactly in the queries the issue is about.

"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 SELECT uniq(number) FROM numbers(100000000) is within 0.1% of master.

SELECT uniq(number) FROM numbers_mt(4000000000)     -- 3979938734    (-0.50%)
SELECT uniq(number) FROM numbers_mt(50000000000)    -- 50090681348   (+0.18%), was 18446743978444128518
SELECT uniq(number) FROM numbers_mt(100000000000)   -- 99642145106   (-0.36%)
SELECT uniq(number) FROM numbers_mt(1000000000000)  -- 1016359869734 (+1.6%)

Memory: unchanged below ~1M distinct per state (plus one pointer in sizeof), n / 16384 bytes from there, at most +50% (768 KiB total) for multi-billion-cardinality states. Estimate error above two billion is ~0.8-1.1% (8192-16384 samples) versus ~0.6% below. The PR description is updated for the new design.

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review August 20, 2026 04:08
`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.
Comment thread src/AggregateFunctions/UniquesHashSet.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d2e857d7a5e0eb938bde8c8c0dea7fc297e1b26d was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

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.
Comment thread src/AggregateFunctions/UniquesHashSet.h Resolved
@mintlify

mintlify Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 3, 2026, 8:52 AM

# 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
alexey-milovidov and others added 3 commits October 5, 2026 00:25
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the two red checks of 631a00f and merged master:

  • Style check: an extra empty line in NativeReader.cpp.
  • Build (arm_tidy): cppcoreguidelines-pro-type-member-init is reported at the implicit constructor of WideCandidates (UniquesHashSet.h:670), not at the values member that carried the NOLINT. Reproduced with local clang-tidy, now clean (cbf389b).
  • After merging master the build broke: IDataType::forEachChild was removed in favor of forEachInTypeTree (d0b1924). getAggregateStateVersions now uses it (d2e857d). The binary builds, and all 19 stateless tests touched by this PR pass locally.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 5, 2026
Merged via the queue into master with commit 1df42b0 Oct 5, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the uniq-64bit branch October 5, 2026 19:36
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 5, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
…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]>
raimannma added a commit to raimannma/ClickHouse that referenced this pull request Oct 9, 2026
…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]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 16, 2026
`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
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 31, 2026
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]>
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Nov 3, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). pr-bugfix Pull request with bugfix, not backported by default 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.

Avoid overflow in aggregate function "uniq"

3 participants