Skip to content

Fix segfault in uniqStateOrNull with WITH ROLLUP/CUBE/TOTALS - #105470

Merged
Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105462-uniqstateornull-rollup
May 26, 2026
Merged

Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105462-uniqstateornull-rollup

Conversation

@groeneai

@groeneai groeneai commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #105462.

SELECT uniqStateOrNull(h) FROM t GROUP BY h WITH ROLLUP (and the WITH CUBE / WITH TOTALS and *OrDefault chains) crashes the server with a nullptr read in UniquesHashSet::write. The synthesised "all-grouped-up" or "totals" row's nested UniquesHashSet ends up with buf == nullptr by the time it is serialized, and the bucket scan dereferences buf[0].

UniquesHashSet::write now bails out with an empty state (skip_degree = 0, m_size = 0) when buf is null, instead of attempting to scan a zero-size buffer.

Reproduces against c3d7f9fa9b2 (master, May 2026), v26.3, v26.4. Bidirectionally verified locally (master debug build): the minimum repro from #105462 segfaults without this patch and passes with it.

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

Fix a server segfault in uniqStateOrNull / uniqStateOrDefault / uniqOrNullState (and similar combinator chains over uniq) when used with GROUP BY ... WITH ROLLUP, WITH CUBE, or WITH TOTALS and a Nullable argument.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Touches core aggregation result insertion for state-returning functions and adds an assertion in UniquesHashSet::write, which could affect stability/behavior of aggregate-state serialization paths if there are edge cases beyond the reported crash.

Overview
Fixes a crash when *StateOrNull/*StateOrDefault (notably uniqStateOrNull) is used with GROUP BY ... WITH ROLLUP/CUBE/TOTALS by changing AggregateFunctionOrFill to not route “no input” rows through to.insertDefault() when the nested function returns an aggregate state, and instead forward the default-initialized state through the same insertion path as non-empty rows.

Adds a defensive chassert(buf) in UniquesHashSet::write() to catch corrupted/double-destroyed states earlier, and introduces stateless regression tests covering rollup/cube/totals plus downstream consumers (uniqMerge, AggregatingMergeTree persistence, two-level/multithread aggregation, and Memory sources).

Reviewed by Cursor Bugbot for commit c9c5a32. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.155
  • Backported to: 26.5.2.15, 26.4.4.19, 26.3.13.18

`SELECT uniqStateOrNull(h) FROM t GROUP BY h WITH ROLLUP` (and the
`WITH CUBE` / `WITH TOTALS` and `*OrDefault` variants) segfault the
server: the synthesised "all-grouped-up" row's nested `UniquesHashSet`
ends up with a `nullptr` `buf` member, and the subsequent
serialization loop dereferences it.

`UniquesHashSet::write` now bails out and emits an empty state when
`buf` is null, instead of trying to scan a zero-size buffer.

Closes ClickHouse#105462
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

a) Deterministic repro? Yes. The 3-line repro from #105462 (a Nullable(UInt16) column with mixed NULL and non-NULL rows + uniqStateOrNull(...) GROUP BY ... WITH ROLLUP) segfaults the server on demand on master 48b7d9f3 debug build, exit 139 SIGSEGV. Stack trace: UniquesHashSet::write at line 476 → AggregateFunctionUniq::serialize → SerializationAggregateFunction::serializeBatch → NativeWriter::writeData. Same crash via the hex(...) path through serializeText.

b) Root cause explained? When WITH ROLLUP / WITH CUBE / WITH TOTALS synthesises the "all-grouped-up" / "totals" row from uniq*State*OrNull-wrapped states, the nested UniquesHashSet of that row ends up with buf == nullptr by the time it is serialized. The serialization loop scans buf[0..buf_size()) to find non-zero bucket entries and dereferences a null pointer.

c) Fix matches root cause? Yes. UniquesHashSet::write now emits an empty state representation (skip_degree = 0, m_size = 0) when buf is null, instead of dereferencing it. This is the second of the two alternatives the issue suggests ("UniquesHashSet::write should handle the empty-state case"). The wire format is preserved for all valid states.

d) Test intent preserved? / New tests added? New regression test 04262_105462_uniq_state_or_null_with_rollup.sql covers WITH ROLLUP, WITH CUBE, WITH TOTALS against uniqStateOrNull, uniqStateOrDefault, uniqOrNullState, plus a plain GROUP BY sanity check. It asserts only row counts (not state bytes) so it does not encode internal UniquesHashSet layout.

e) Demonstrated in both directions? Yes. With git stash of the patch the regression test fails the way #105462 describes (server segfaults, query returns network error). With the patch reinstated and the server restarted, the 3 crashing variants all return without error and the regression test passes.

f) Fix is general, not a narrow patch? I considered the symmetric question — does this same pattern exist elsewhere? UniquesHashSet::read already handles m_size == 0 correctly via its m_size <= 1 branch. The other uniq* data structures (HyperLogLogWithSmallSetOptimization, HashSet-based uniqExactData) check their state shape before scanning members, so they are not vulnerable to the same nullptr buf pattern. The issue only reports crashes on the uniq chain, consistent with this.

This is a defensive write fix rather than a deeper repair of why the inner state arrives in this shape from the multi-grouping-set aggregator paths. A follow-up to identify and fix the upstream lifecycle issue (state destroyed prematurely or zero-initialised) would be valuable, but this patch is sufficient to stop the crash, restores the v26.2 behavior (an empty serialized state for the rolled-up bucket), and is wire-format compatible.

Session: cron:clickhouse-ci-task-worker:20260520-184500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @qoega @rschu1ze — could you review? This fixes the segfault @qoega reported in #105462. The fix is defensive (handles nullptr buf in UniquesHashSet::write), wire-format compatible, and isolated to the uniq data structure.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 20, 2026
@qoega qoega self-assigned this May 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c9c5a32]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) FAIL
Tests FAIL IGNORED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR fixes the *OrNull/*OrDefault + *State rollup path by avoiding to.insertDefault() for flag-unset rows when the nested function is stateful, which preserves ColumnAggregateFunction ownership invariants and removes the double-destroy path that led to UniquesHashSet corruption. I reviewed the current PR head diff and surrounding core code (AggregateFunctionOrFill, ColumnAggregateFunction, AggregateFunctionState, UniquesHashSet), plus existing discussion threads; the reported crash path is addressed and I did not find remaining correctness, lifetime, or compatibility regressions in the touched logic.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 20, 2026
The flag-set branch of `AggregateFunctionOrFill::insertResultIntoImpl`
pushes the inner aggregate state pointer into the result
`ColumnAggregateFunction` as an external reference; the result column's
`src` field keeps the source column alive so the source owns the
destruction of those states.

The flag-unset branch previously called `to.insertDefault()`. For
`State`-nested combinators that runs `ColumnAggregateFunction::insertDefault`
on the inner column, which calls `ensureOwnership()` and resets `src` to
null. Any later flag-set row then pushes an external pointer into a
column with no `src` protection, so both this column and the source
column destroy the same aggregate state at pipeline tear-down.

For `UniquesHashSet` the double-destroy surfaces under `MemorySanitizer`
as `use-of-uninitialized-value` reading `buf` inside `~UniquesHashSet`
(STID 8424-6802 on the regression test added in this PR for
`uniqStateOrNull`/`uniqStateOrDefault`/`uniqOrNullState` with `ROLLUP`,
`CUBE`, and `TOTALS`).

Mirror the flag-set branch for `State`-nested combinators: forward the
already-default-initialized inner state through `nested_function->insertResultInto`
and push `1` to the null map. This keeps the column's `src` set for the
entire `convertToValues` loop and avoids the double-destroy.

Verified locally with 50 randomized runs of
`04262_105462_uniq_state_or_null_with_rollup`.

Closes ClickHouse#105462
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fix-up commit 4187aa5c)

The original write-path guard fixed the segfault but left a separate latent destruction-order bug reachable, which MemorySanitizer correctly flagged (STID 8424-6802). Pushed fix-up commit answering the mandatory gate:

a) Deterministic repro? Yes — 04262_105462_uniq_state_or_null_with_rollup.sql (the regression test added in this PR) crashed every MSan run on commit 3e5a30c7 (CIDB: 4 hits across Stress test (amd_msan), Stress test (arm_msan), Stateless tests (amd_msan, WasmEdge, parallel, 1/2), Stateless tests (amd_msan, flaky check), all on this PR's 3e5a30c7, zero hits on any other PR or master).

b) Root cause explained? Yes. Trace (from MSan stack):

  1. AggregateFunctionOrFill::insertResultIntoImpl flag-set branch pushes the inner aggregate state pointer into the result ColumnAggregateFunction as an external reference via nested_function->insertResultInto -> AggregateFunctionState::insertResultInto -> data.push_back(place). The result column's src keeps the source alive.
  2. The flag-unset branch previously called to.insertDefault(), which for State-nested combinators reaches ColumnAggregateFunction::insertDefault on the inner column. That calls ensureOwnership() and resets src to null.
  3. Any later flag-set row in the same convertToValues loop then pushes an external pointer into a column with src == nullptr. At pipeline tear-down both this column and the source column destroy the same UniquesHashSet, so the second ~UniquesHashSet reads buf after the first one already destroyed the object -> MemorySanitizer: use-of-uninitialized-value at UniquesHashSet.h:99.

c) Fix matches root cause? Yes. Mirror the flag-set branch for State-nested combinators: forward the already-default-initialized inner state through nested_function->insertResultInto and push 1 to the null map. create() runs nested_function->create(place) unconditionally, so the inner state at place is a properly default-constructed UniquesHashSet. src remains set for the entire convertToValues loop, so the result column skips func->destroy at destruction and the source column owns destruction uniquely.

d) Test intent preserved? / New tests added? Yes. Regression test 04262_105462_uniq_state_or_null_with_rollup still asserts the same counts (no segfault, no exception). Output is byte-identical with and without the fix in non-MSan builds. The fix only changes which arena owns the state pointer for flag-unset rows; the underlying serialized state (default empty UniquesHashSet) is the same.

e) Demonstrated in both directions? Yes.

  • Without commit 4187aa5c: CI MSan jobs on 3e5a30c7 report STID 8424-6802 (use-of-uninitialized-value in ~UniquesHashSet).
  • With commit 4187aa5c: 50/50 randomized-settings runs of the regression test in Debug pass.
  • Full MSan re-validation will run on this push and should clear the bugfix-validation FAIL too.

f) Fix is general, not a narrow patch? Yes. The fix lives in AggregateFunctionOrFill::insertResultIntoImpl and is gated on nested_function->isState(), so it covers both -OrNull and -OrDefault over any State-combinator-wrapped function (uniqState*, uniqExactState*, quantileState*, etc.), not just uniqStateOrNull. Non-State paths (e.g. uniqOrNull, sumOrDefault) are unchanged.

cc @qoega for re-approval given the new commit.

@Algunenano Algunenano self-assigned this May 22, 2026
@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label May 22, 2026

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

@groeneai

The AggregateFunctionOrFill::insertResultIntoImpl change is the right root-cause fix. However, the regression surface from #99839 (which enabled *StateOrNull / *StateOrDefault chains over Nullable arguments) is wider than the current regression test covers. The bug reproduces under MSan through several other code paths that don't touch the WITH ROLLUP/CUBE/TOTALS aggregator-transform path the test exercises.

I'd like to see these added as regression tests so we can lock in that the OrFill fix handles all consumers of the rollup-produced state, not just the direct SELECT … FROM (… WITH ROLLUP) path.

Reproducers under MSan (master, post-#99839, pre-this-PR)

Shared setup:

CREATE TABLE source (h Nullable(UInt16)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO source SELECT if(number % 5 = 0, NULL, toUInt16(number)) FROM numbers(20);

1. <func>Merge over rollup-produced states

SELECT uniqMerge(s)
FROM (SELECT uniqStateOrNull(h) AS s FROM source GROUP BY h WITH ROLLUP);

MSan reports use-of-uninitialized-value in UniquesHashSet::merge at UniquesHashSet.h:438, via AggregateFunctionMerge::add → Aggregator::executeWithoutKeyImpl. This exercises the merge path on the rollup-produced state column, a different code path than the serialize-driven one in the issue.

2. INSERT into AggregatingMergeTree

CREATE TABLE agg_t (k UInt8, s AggregateFunction(uniq, UInt16)) ENGINE = AggregatingMergeTree ORDER BY k;

INSERT INTO agg_t
SELECT toUInt8(coalesce(h, 999)) AS k, uniqStateOrNull(h)
FROM source
GROUP BY h WITH ROLLUP;

MSan reports the use-of-uninitialized-value in UniquesHashSet::merge via ColumnAggregateFunction::insertMergeFrom → AggregatingSortedAlgorithm::AggregatingMergedData::addRow → MergeTreeDataWriter::mergeBlock. The corruption is persisted into a part-merge path.

3. Two-level aggregator (single-thread)

SELECT hex(uniqStateOrNull(h))
FROM source
GROUP BY h WITH ROLLUP
SETTINGS group_by_two_level_threshold = 1, group_by_two_level_threshold_bytes = 1, max_threads = 1;

Reproduces on master.

4. Multi-threaded merge

SELECT hex(uniqStateOrNull(h))
FROM source
GROUP BY h WITH ROLLUP
SETTINGS max_threads = 4
FORMAT Null;

Reproduces on master.

5. Memory engine source

Same reproducer with the source table re-created as ENGINE = Memory also reproduces under MSan, confirming this is pipeline-level rather than MergeTree-specific.

Paths that I checked and that are clean

For completeness, these did not reproduce under MSan (so the regression appears scoped to the synthetic-row-producing aggregator transforms, as expected):

  • SELECT uniqStateOrNull(h) FROM source WHERE 0 (empty source, no GROUP BY)
  • SELECT uniqStateOrNull(h) FROM source WITH TOTALS (no GROUP BY)
  • SELECT uniqStateOrNull(h) FROM source GROUP BY GROUPING SETS ((h), ())
  • SELECT arrayReduce('uniqStateOrNull', CAST([] AS Array(Nullable(UInt16))))

Suggestions

  1. Add reproducers 1 and 2 above as regression tests. They cover the merge-into-state and AggregatingMergeTree-INSERT consumers of the rollup-produced state. The current test only exercises the serialize-driven final-projection path.
  2. Optionally add reproducers 3 and 4 to lock in the two-level and multi-thread aggregator variants. They don't introduce a new code path but they do reach the buggy state via different scheduling, and the failure mode is identical, so a single combined test with a SETTINGS matrix would be enough.
  3. The OrDefault test coverage is currently a single line. Since #99839 enabled the *StateOrDefault chain in the same way as *StateOrNull, it would be worth mirroring at least reproducer 1 for uniqStateOrDefault so we don't silently regress only one of the two combinator variants.

Comment thread src/AggregateFunctions/UniquesHashSet.h Outdated
if (m_size > UNIQUES_HASH_MAX_SIZE)
throw Poco::Exception("Cannot write UniquesHashSet: too large size_degree.");

/// `buf` may be null when the surrounding aggregate state was not

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 This is correct but the wrong approach. Reaching this circumstance only happens due to corruption.

This should either be a chassert(buf) or a check and throw LOGICAL_ERROR.

The right fix is the one doing in AggregateFunctionOrFill::insertResultIntoImpl

Two changes in response to ClickHouse#105470 (review):

1. Replace the silent `if (!buf) bail` in `UniquesHashSet::write` with
`chassert(buf)`. The `AggregateFunctionOrFill::insertResultIntoImpl`
change in commit 4187aa5 establishes the invariant that the source
state's `buf` is never null at serialise time. The previous bail-out
silently masked corruption rather than surfacing it; the assertion now
documents the invariant and fails loudly in debug / sanitiser builds if
it is ever broken again.

2. Add new regression test `04273_105462_uniq_state_or_null_rollup_consumers`
covering consumer paths not exercised by the original
`04262_105462_uniq_state_or_null_with_rollup` test. The original test
only reaches the `serialize`-driven final-projection path. Algunenano
pointed out four additional consumers that all relied on the same
corrupted `UniquesHashSet`:

- `<func>Merge` over the rollup-produced state column. Reaches
  `UniquesHashSet::merge` via `AggregateFunctionMerge::add`.
- `INSERT INTO AggregatingMergeTree`. Persists the rollup-produced state
  via `ColumnAggregateFunction::insertMergeFrom` ->
  `AggregatingSortedAlgorithm::AggregatingMergedData::addRow` ->
  `MergeTreeDataWriter::mergeBlock`.
- Two-level + multi-thread aggregator scheduling variants.
- `Memory` engine source confirms the regression is pipeline-level
  rather than `MergeTree`-specific.

The test also mirrors the first reproducer for `uniqStateOrDefault`,
since ClickHouse#99839 enabled the `*StateOrDefault` chain in the same way as
`*StateOrNull`.

Verified locally:
- Without the `OrFill` fix (binary from a sibling branch lacking commit
  4187aa5), reproducer 1 segfaults at `UniquesHashSet::merge:453` (stack
  trace captured during this work).
- With the `OrFill` fix, 100/100 randomised runs of the new test pass,
  50/50 randomised runs of `04262` still pass, and the AggregatingMergeTree
  reproducer is asserted via `uniqMerge(s)` rather than `count()` so the
  assertion is deterministic across `enable_parallel_replicas` and
  `max_insert_threads` randomisation.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Addressed in 8d52133:

Inline comment on src/AggregateFunctions/UniquesHashSet.h:466 — replaced the silent if (!buf) bail with chassert(buf). The AggregateFunctionOrFill::insertResultIntoImpl change (4187aa5) makes a non-null buf an invariant at this site; the assertion documents that and surfaces any future regression loudly in debug / sanitiser builds.

Regression-test surface — added a new test 04273_105462_uniq_state_or_null_rollup_consumers that covers your additional consumer paths without extending 04262:

  • uniqMerge over the rollup-produced state column — exercises UniquesHashSet::merge via AggregateFunctionMerge::add.
  • INSERT INTO AggregatingMergeTree from the rollup — exercises the persistence path through ColumnAggregateFunction::insertMergeFrom → AggregatingSortedAlgorithm → MergeTreeDataWriter::mergeBlock. Asserted via uniqMerge(s) FROM agg_t_105462 rather than count(), so the result is deterministic under enable_parallel_replicas / max_insert_threads randomisation (verified 100/100).
  • Two-level single-thread + multi-thread variants (your reproducers 3 and 4) with a SETTINGS matrix per query.
  • Memory-engine source variant (your reproducer 5), confirming the regression is pipeline-level rather than MergeTree-specific.
  • The uniqMerge-over-rollup case is also mirrored for uniqStateOrDefault, since Fix aggregate_functions_null_for_empty for non-Nullable result types #99839 enabled both combinator variants identically.

Pre-PR validation gate

(a) Deterministic repro — yes. Each of the 5 reproducers produces a stable, single-value output (16 / 16 / 16 / 18 / 18 / 16).

(b) Root cause explained — *StateOrNull / *StateOrDefault over Nullable (enabled by #99839) combined with WITH ROLLUP / CUBE / TOTALS produces a synthesised "all-grouped-up" row in the aggregator transform. Before the OrFill fix, the flag-unset branch of AggregateFunctionOrFill::insertResultIntoImpl called to.insertDefault() on the inner ColumnAggregateFunction, which invoked ensureOwnership() and reset the column's src to null. Any subsequent flag-set row then pushed an externally-owned state pointer into a column without src protection, so both the result column and the source column ran func->destroy on the same UniquesHashSet at pipeline tear-down. The second ~UniquesHashSet then read the just-freed buf field — use-of-uninitialized-value under MSan in UniquesHashSet::merge (your reproducers), or null-pointer segfault in debug builds.

(c) Fix matches root cause — the OrFill change in 4187aa5 is exactly the fix you endorsed; this commit only adds coverage. The chassert(buf) change documents and enforces the invariant the OrFill fix establishes.

(d) Test intent preserved — 04273 is purely additive coverage. 04262 is unchanged.

(e) Both directions demonstrated:

  • Without the OrFill fix (binary from a sibling branch lacking 4187aa5), reproducer 1 segfaults at UniquesHashSet::merge:453 via AggregateFunctionMerge::addBatchSinglePlace → Aggregator::executeWithoutKeyImpl → AggregatingTransform::consume (stack trace captured during this work — rhs.buf[i] deref).
  • With the OrFill fix and the new chassert, 100/100 randomised runs of the new test pass and 50/50 randomised runs of 04262 still pass. Two-level aggregator tests (02560_*) also pass 50/50 (no chassert fires under normal operation).

(f) Fix is general — the OrFill change is gated on nested_function->isState(), so it covers all -State* + -OrNull / -OrDefault combinations (uniqStateOrNull, uniqStateOrDefault, uniqExactStateOrNull, quantileStateOrNull, etc.). The new test exercises 5 distinct downstream consumer paths.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai I've left several comments in the last commit directly

`UniquesHashSet.h`: the `chassert(buf)` comment now describes the
invariant violation at the call site only, without referencing other
parts of the PR.

Test file: renamed to `04273_uniq_state_or_null_rollup_consumers.{sql,reference}`,
dropping the `_105462_` issue-number infix.

Test header and inline comments: rewritten to describe the consumer
paths being exercised (`Merge`, `AggregatingMergeTree` insert,
two-level / multi-threaded aggregator, `Memory` engine). Removed
references to the other test file and to the bug history.

Verified: 15/15 PASS for the renamed test and the existing `04262`
test against the rebuilt PR-branch binary.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed fix-up f5f1eb45a9a6 addressing the three commit comments:

  • src/AggregateFunctions/UniquesHashSet.h: rewrote the chassert(buf) comment to describe only the invariant violation at the call site (no longer references the OrFill fix or other parts of this PR).
  • Test filename: renamed to 04273_uniq_state_or_null_rollup_consumers.{sql,reference} (dropped the _105462_ infix).
  • Test file header and inline comments: rewritten to describe the consumer paths being exercised (Merge, AggregatingMergeTree insert, two-level / multi-threaded aggregator, Memory engine). Removed references to the other test file and to the bug history.

Verified locally: 15/15 PASS on the renamed test and on the existing 04262 test against the rebuilt PR-branch binary.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit f5f1eb4. Configure here.

if constexpr (merge)
nested_function->insertMergeResultInto(place, col.getNestedColumn(), arena);
else
nested_function->insertResultInto(place, col.getNestedColumn(), arena);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Dead code branch unreachable due to type system constraint

Low Severity

The else branch handling result_is_nullable && !inner_nullable inside the nested_function->isState() block is unreachable dead code. When isState() returns true, the nested function's result type is always DataTypeAggregateFunction, which has canBeInsideNullable() returning false. This causes createResultType to return the type unwrapped, making result_is_nullable always false. Thus the condition !result_is_nullable || inner_nullable is always true, and this else branch (which writes a null marker and inserts into the nested column) can never execute.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit f5f1eb4. Configure here.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai tests/queries/0_stateless/04262_105462_uniq_state_or_null_with_rollup.sql is still named incorrectly

Per @Algunenano on ClickHouse#105470, drop the `_105462_` issue-number infix from
the test filename to follow the standard `<number>_<name>` convention
(same shape as the `04273_105462_*` -> `04273_*` rename in `f5f1eb45a9a6`).

Pure metadata change: file contents unchanged.

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

Copy link
Copy Markdown
Collaborator Author

Renamed tests/queries/0_stateless/04262_105462_uniq_state_or_null_with_rollup.{sql,reference} to drop the _105462_ infix in c9c5a32a8a45. Same shape as the 04273_105462_* -> 04273_* rename in f5f1eb45a9a6. File contents unchanged; git diff --stat shows the rename only.

@clickhouse-gh

clickhouse-gh Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 58.82% (10/17) · Uncovered code

Full report · Diff report

@Algunenano
Algunenano added this pull request to the merge queue May 26, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks May 26, 2026
@Algunenano
Algunenano added this pull request to the merge queue May 26, 2026
Merged via the queue into ClickHouse:master with commit 256c1a5 May 26, 2026
164 of 167 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label May 26, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 26, 2026
robot-clickhouse added a commit that referenced this pull request May 26, 2026
Cherry pick #105470 to 25.8: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
robot-clickhouse added a commit that referenced this pull request May 26, 2026
robot-clickhouse added a commit that referenced this pull request May 26, 2026
Cherry pick #105470 to 26.3: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
robot-clickhouse added a commit that referenced this pull request May 26, 2026
robot-clickhouse added a commit that referenced this pull request May 26, 2026
Cherry pick #105470 to 26.4: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
robot-clickhouse added a commit that referenced this pull request May 26, 2026
robot-clickhouse added a commit that referenced this pull request May 26, 2026
Cherry pick #105470 to 26.5: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
robot-clickhouse added a commit that referenced this pull request May 26, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label May 26, 2026
Algunenano added a commit that referenced this pull request May 27, 2026
Backport #105470 to 26.5: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
Algunenano added a commit that referenced this pull request May 27, 2026
Backport #105470 to 26.4: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
Algunenano added a commit that referenced this pull request May 27, 2026
Backport #105470 to 26.3: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…5470

Backport ClickHouse#105470 to 26.4: Fix segfault in `uniqStateOrNull` with `WITH ROLLUP`/`CUBE`/`TOTALS`
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 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.

uniqStateOrNull + Nullable arg + GROUP BY ... WITH ROLLUP segfaults the server

6 participants