Skip to content

Fix server crash in -State aggregate combinators with WITH ROLLUP/CUBE/TOTALS + ORDER BY - #105749

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105742-uniq-state-rollup-order-by
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105742-uniq-state-rollup-order-by

Conversation

@groeneai

@groeneai groeneai commented May 24, 2026 •

Copy link
Copy Markdown
Collaborator

Issue #105742, also fixes #105740 (and root cause of chronic #102460).

Stack on master (840494d51c9):

0. UniquesHashSet<...>::merge      AggregateFunctions/UniquesHashSet.h:453   (NULL deref of buf)
1. ColumnAggregateFunction::ensureOwnership      Columns/ColumnAggregateFunction.cpp:258
2. ColumnAggregateFunction::insertDefault        Columns/ColumnAggregateFunction.cpp:649
3. ColumnAggregateFunction::insertFromWithOwnership  Columns/ColumnAggregateFunction.cpp:558
4. ColumnAggregateFunction::insertRangeFrom      Columns/ColumnAggregateFunction.cpp:316
5. MergeSorter::mergeBatchImpl                   Processors/Transforms/SortingTransform.cpp:136

Reproducer (5 lines after creating the source tables from the issue):

SELECT s1.g, uniqStateOrDefault(b)
FROM _s1 AS s1
LEFT JOIN _s2 AS s2 ON s1.a = s2.x
GROUP BY s1.g WITH ROLLUP WITH TOTALS
ORDER BY s1.g DESC NULLS FIRST
FORMAT Null;

Root cause

ColumnAggregateFunction::convertToValues calls func->insertResultInto for each row in the source column. For State combinators (e.g. AggregateFunctionState::insertResultInto) this path is optimized to push the source state pointer into res.data without copying, relying on res.src to keep the source column alive.

uniqStateOrDefault is AggregateFunctionOrFill<false> around AggregateFunctionState(AggregateFunctionUniq). OrFill::insertResultIntoImpl has two branches:

  • flag=1 (state was populated): delegates to nested_function->insertResultInto -> State::insertResultInto -> pushes place directly.
  • flag=0 (no input rows ever added): calls to.insertDefault().

ColumnAggregateFunction::insertDefault calls ensureOwnership first, and ensureOwnership always finishes with src.reset(). So once a single flag=0 row is processed, res.src is null. Any subsequent flag=1 row still pushes a raw pointer into res.data, but res no longer holds a reference to the source column. When convertToValues returns and the source column gets destructed, the source column's destructor calls func->destroy on every state in its data, and those destructors zero out internal pointers (for uniq, UniquesHashSet::~UniquesHashSet -> free() sets buf = nullptr, while m_size is unchanged at its last value, e.g. 33).

Sorting then read those pointers (MergeSortingTransform -> insertRangeFrom -> ensureOwnership -> IAggregateFunction::merge) and dereferenced the destructed state, segfaulting at UniquesHashSet.h:453 (rhs.buf[i]).

Relation to #105740 / #102460

convertToValues is the call path behind every finalizeChunk(chunk, mask) (it walks each masked column and replaces it with convertToValues(...)). All four transforms that produce finalized aggregate columns - CubeTransform, RollupTransform, TotalsHavingTransform, AggregatingInOrderTransform - go through the same call site. So the four sanitizer signatures qoega listed in #105740 (TSan iterator invalidation under CubeTransform, ASan single/cross-thread, MSan via TotalsHavingTransform) and the chronic jemalloc heap-corruption surfaces in #102460 are different downstream observations of the same upstream aliasing bug fixed here. singleValueOrNullStateOrDefault, argMaxStateOrDefault, etc. are all State combinators that share this code path, so the fix is general.

Fix

Use insertMergeResultInto in convertToValues instead of insertResultInto. For State combinators (State, OrFill, Null, Resample, ForEach, ...) insertMergeResultInto forces a real copy via to.insertFrom(place), so every entry in res.data ends up owned by res. For non-State aggregate functions the default IAggregateFunction::insertMergeResultInto just delegates to insertResultInto, so behavior is unchanged for them.

Tests

Existing related tests still pass (00701_rollup, 01122_totals_rollup_having_block_header, 00388_enum_with_totals, 00150_with_totals_and_join, 00597_with_totals_on_empty_set, 00906_low_cardinality_rollup, 00804_rollup_with_having).

Documentation entry for user-facing changes

  • Documentation update is not required

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 server crash and use-after-free in ColumnAggregateFunction::convertToValues when materializing a -State aggregate column from WITH ROLLUP, WITH CUBE or WITH TOTALS followed by ORDER BY. The crash manifested as a NULL dereference in UniquesHashSet::merge (for uniq*State) or sanitizer use-after-free / use-of-uninitialized (for other State combinators such as singleValueOrNullState and argMaxState).

Closes #105742

…OTALS + ORDER BY (ClickHouse#105742)

`ColumnAggregateFunction::convertToValues` called `func->insertResultInto`, which
for State combinators (e.g. via `AggregateFunctionState::insertResultInto`) pushes
the source state pointer into `res.data` without copying. This relies on `res.src`
keeping the source column alive.

For `-OrFill` (i.e. `-OrDefault`/`-OrNull`) wrappers around a State function
(`uniqStateOrDefault`, etc.), the flag=0 branch of `insertResultIntoImpl` calls
`res.insertDefault` -> `res.ensureOwnership` which resets `res.src`. After that,
the very next flag=1 row would push another raw pointer into `res.data` while
nothing kept the source column alive: when `convertToValues` returns and the
source column is destroyed, those pointers dangle into destructed state objects.

A downstream consumer that then walked those pointers (e.g.
`MergeSortingTransform` -> `MergeSorter::mergeBatchImpl` -> `insertRangeFrom` ->
`ensureOwnership` -> `IAggregateFunction::merge`) would read the destructed state.
For `uniq`/`uniqState` the destructor sets `UniquesHashSet::buf = nullptr` (while
m_size remained at its last value, e.g. 33), so the indexing at line 453 of
`UniquesHashSet.h` dereferenced a null pointer -> server SEGV. Other State
combinators that depend on the inner state in their destructor showed analogous
crashes / UB.

Fix: use `insertMergeResultInto` in `convertToValues` instead. For State
combinators this forces a copy via `to.insertFrom(place)`, so every entry in
`res.data` ends up owned by `res`. For non-State functions the default
`IAggregateFunction::insertMergeResultInto` just delegates to `insertResultInto`,
so no behavior change for the common path.

Reproducer: `SELECT g, uniqStateOrDefault(v) FROM t GROUP BY g WITH ROLLUP
ORDER BY g DESC FORMAT Null` where one of the groups has all-NULL values for
`v` (so its OrFill flag byte stays 0 and triggers `res.insertDefault` in
`convertToValues`).

Closes ClickHouse#105742.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md Phase 4 step 9):

a) Deterministic repro: yes - 5-line query from #105742 SEGVs on master 41656be24cc8, UBSan reports load of null pointer at UniquesHashSet.h:453. Reproduces with smaller queries too (no JOIN, ~10 rows) as long as one group has all-NULL inputs and the result is ORDER-BY'd.

b) Root cause explained: yes. convertToValues pushes shared pointers via State::insertResultInto, relies on res.src to keep source alive. OrFill::insertResultIntoImpl flag=0 calls res.insertDefault -> res.ensureOwnership which resets res.src. Subsequent flag=1 rows then push raw pointers with no reference holding the source; when the source column gets destructed at end of convertToValues, those pointers dangle into destructed states. Detailed walkthrough in the PR body.

c) Fix matches root cause: yes. insertMergeResultInto makes every State-combinator state get copied into res's own arena (to.insertFrom(place)), so res.data is fully owned by res regardless of how many flag=0/flag=1 transitions happen during the loop. Source column can be destroyed safely after convertToValues returns.

d) Test intent preserved + new tests added: yes. 04275_105742_uniq_state_or_default_rollup_order_by.sql exercises WITH ROLLUP, WITH ROLLUP WITH TOTALS, WITH CUBE, and bare uniqState followed by ORDER BY. Existing related tests still pass (00701_rollup, 01122_totals_rollup_having_block_header, 00388_enum_with_totals, 00150_with_totals_and_join, 00597_with_totals_on_empty_set, 00906_low_cardinality_rollup, 00804_rollup_with_having).

e) Demonstrated in both directions: yes. Verified by stashing the fix, rebuilding ASan, and running the new test - UBSan fires at UniquesHashSet.h:453 with summary undefined-behavior /home/ubuntu/nerve-workspace/ClickHouse/src/AggregateFunctions/UniquesHashSet.h:453:17. After restoring the fix and rebuilding, the test prints ok.

f) Fix is general: yes. The fix is at the convertToValues call site, not at the symptom site. All State combinators (-State, -OrFill (-OrDefault/-OrNull), -Null, -Resample, -ForEach) override insertMergeResultInto to copy via to.insertFrom(place). So any combinator that depended on the inner state's destructor (not just uniq) is now safe. Non-State functions fall through to the default IAggregateFunction::insertMergeResultInto which delegates to insertResultInto, so they keep the existing fast path.

Session: cron:clickhouse-ci-task-worker:20260524-194500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @rschu1ze @KochetovNicolai - could you review? This fixes a server SEGV in any -State aggregate that runs through ColumnAggregateFunction::convertToValues (#105742). The patch is a one-line change in convertToValues (use insertMergeResultInto instead of insertResultInto) plus a regression test.

…combinator UAF)

Same convertToValues root cause as ClickHouse#105742, manifesting via TotalsHavingTransform
instead of RollupTransform / MergeSorter, and across additional State combinators
(singleValueOrNullState, argMaxState). The fix in ClickHouse#105749 already addresses this
because it patches the upstream `ColumnAggregateFunction::convertToValues` call
site that every finalizeChunk caller (CubeTransform, RollupTransform,
TotalsHavingTransform, AggregatingInOrderTransform) routes through.

Verified pre-fix UBSan fires at UniquesHashSet.h:453 on the CUBE variant
(`runtime error: load of null pointer of type 'HashValue'`); post-fix the test
passes on both Debug and ASan builds.

Closes ClickHouse#105740. Should also close the chronic jemalloc heap-corruption family
issue ClickHouse#102460 since ClickHouse#105740 is its identified upstream root cause.
@groeneai groeneai changed the title Fix server crash in uniqStateOrDefault with WITH ROLLUP/CUBE/TOTALS + ORDER BY Fix server crash in -State aggregate combinators with WITH ROLLUP/CUBE/TOTALS + ORDER BY May 24, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f0dbe2f]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
01018_Distributed__shard_num FAIL cidb

AI Review

Summary

This PR changes ColumnAggregateFunction::convertToValues to use insertMergeResultInto instead of pointer-sharing insertResultInto when materializing aggregate-state columns. That removes a real lifetime hazard for -State combinators under WITH ROLLUP / WITH CUBE / WITH TOTALS + ORDER BY, and the added regression tests cover the affected paths (RollupTransform, CubeTransform, and TotalsHavingTransform). I did not find unresolved correctness, safety, performance, or PR-metadata issues in the current head.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 25, 2026
@azat azat self-assigned this May 25, 2026
The .sql versions crash the shared clickhouse-server, which is the bug they
target. On the PR (with the fix) they pass cleanly, but on master (Bugfix
validation) the server crash races with the test runner's parallel cleanup:
clickhouse-test detects the dead server, but the cleanup sleep/terminate
sequence is interrupted by a second SIGTERM, so the runner exits with code 1
instead of STOP_TESTING_EXIT_CODE (2). The job-side parser then takes the
"runner terminated unexpectedly" branch (no per-test FAIL added), the bugfix
inversion sees no FAIL to flip to OK, and the check reports
"Failed to reproduce the bug" even though a core dump for the same SEGV
(QueryPullPipeEx -> ColumnAggregateFunction::convertToValues) is present
in the job artifacts.

Running the same queries via clickhouse-local keeps the SEGV inside a
subprocess: the .sh exits with code 139, clickhouse-test records EXIT_CODE
FAIL, and Bugfix validation correctly flips it to OK ("Bug reproduced").
On the PR branch the fix is in place, all queries finish, the script prints
'ok' and matches the existing .reference.

Reference files keep their original content. Verified locally on master HEAD
build (no fix): both .sh tests fail with return code 139 under
clickhouse-test.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed f0dbe2f14c30 to address the Bugfix validation (functional tests) failure.

Root cause of the validation failure (not the original bug): the .sql regression tests crash the shared clickhouse-server, which is the exact bug they reproduce. The crash is observable in the validation artifacts (core.QueryPullPipeEx.1588-3969.zst.enc, stack ending in ColumnAggregateFunction::convertToValues). What goes wrong from there is in the harness, not the bug:

  • clickhouse-test's check_server_liveness detects the dead server, logs Unable to locate any ClickHouse server process, calls stop_tests(), sleeps 5s, then p.terminate()s the worker pool (tests/clickhouse-test:4929-4942).
  • During that cleanup window a second SIGTERM interrupts the runner. The first signal is caught by the top-level Terminated handler at line 6609, but the next signal hits inside print(...) and re-raises, so the runner exits with code 1 instead of STOP_TESTING_EXIT_CODE = 2.
  • ci/jobs/scripts/functional_tests_results.py:191 only synthesizes the "Server died" FAIL leaf when runner_exit_code == STOP_TESTING_EXIT_CODE. With exit 1 it falls through to elif not s.success_finish → state = ERROR, info "The test runner was terminated unexpectedly", and the per-test list is empty.
  • The bugfix inversion at functional_tests.py:751-762 then iterates test_result.results (now empty), finds nothing to flip, sets has_failure = False, and prints "Failed to reproduce the bug" despite the core dump.

Fix: run the same queries via clickhouse-local instead of against the shared server. The SEGV is now contained in a subprocess; the .sh exits with code 139; clickhouse-test records EXIT_CODE FAIL; the bugfix inversion flips it to OK with has_failure = True. On the PR (fix in place) the queries finish and the script prints ok, matching the unchanged .reference. The fix itself is unchanged in this push (only the test files moved from .sql to .sh).

Locally verified on master HEAD (no fix): both tests fail with return code: 139 under clickhouse-test.

@clickhouse-gh

clickhouse-gh Bot commented May 25, 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.60% 76.60% +0.00%

Changed lines: 100.00% (5/5) · Uncovered code

Full report · Diff report

groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 25, 2026
…rom form

The original fuzzer query uses groupArrayMovingAvgStateDistinctOrDefaultDistinctOrNull
with WITH ROLLUP, which triggers a separate pre-existing trunk bug (ClickHouse#105740 / ClickHouse#105742)
in ColumnAggregateFunction::convertToValues under MSan. The fix for that bug lives
in ClickHouse#105749 (currently open). The minimised isNotDistinctFrom form alone still
exercises the partial-evaluation path that ClickHouse#105650 was concerned about and produces
the same .reference output.

Locally verified 5/5 passes via clickhouse-test with randomized settings.
@qoega

qoega commented May 25, 2026

Copy link
Copy Markdown
Member

@groeneai can you create an issue to fix bug check harness logic and treat crash on old version as fail. Once created also implement a fix for it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@qoega filed the tracking issue and a fix PR for the bugfix-validation harness side of the problem you flagged:

Companion to #105643 (@leshikus) which expands the parser's recognized exit codes so SIGTERM/SIGKILL-killed runs surface a synthetic Server died FAIL leaf. Together: #105643 catches signal-killed crashes; #105795 catches every other path that ends in ERROR.

qoega pushed a commit that referenced this pull request May 26, 2026
… UAF)

Same convertToValues root cause as #105742, manifesting via TotalsHavingTransform
instead of RollupTransform / MergeSorter, and across additional State combinators
(singleValueOrNullState, argMaxState). The fix in #105749 already addresses this
because it patches the upstream `ColumnAggregateFunction::convertToValues` call
site that every finalizeChunk caller (CubeTransform, RollupTransform,
TotalsHavingTransform, AggregatingInOrderTransform) routes through.

Verified pre-fix UBSan fires at UniquesHashSet.h:453 on the CUBE variant
(`runtime error: load of null pointer of type 'HashValue'`); post-fix the test
passes on both Debug and ASan builds.

Closes #105740. Should also close the chronic jemalloc heap-corruption family
issue #102460 since #105740 is its identified upstream root cause.
@qoega

qoega commented May 26, 2026 •

Copy link
Copy Markdown
Member
  • 01018_Distributed__shard_num looks flaky. I do not see open issue about it. If it is not present please create one.
  • Try to fix 01018_Distributed__shard_num in separate PR
  • Update this PR to rerun CI

When you see test failures in CI it is good to check if it is related to the change. If not you should check if it was failing on master and in different PRs and perform steps above for every new CI failure.

@groeneai

@PedroTadim

Copy link
Copy Markdown
Member

Closes #105742

@azat

azat commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

(and root cause of chronic #102460).

@groeneai and @qoega I don't think it is related to this issue, the repro there does not have any WITH ROLLUP/CUBE/TOTALS

@azat

azat commented Jun 2, 2026

Copy link
Copy Markdown
Member

And I think #105470 is a better fix, since it does not have overhead for other paths, does it fixes all issues that this PR addresses?

@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

@azat you're right on both counts, thanks for the careful review.

1. The #102460 link was wrong. #102460 is the jemalloc/LTO fantom-crash tracker, no ROLLUP/CUBE/TOTALS involved. I conflated it via the #105740 fuzzer report. Dropping that claim.

2. #105470 is the better fix and already covers #105742. #105470 (merged 256c1a5, 2026-05-26) removes the to.insertDefault() -> ensureOwnership() -> src reset for State-nested -OrFill combinators at the source, which is exactly the mechanism behind #105742 (uniqStateOrDefault = uniq+State+OrFill, synthesized empty-group row hits the flag=0 path). My convertToValues change here is downstream of that and adds insertMergeResultInto overhead on every state path, so it's redundant now.

Verified on current master 26.6.1.338 (includes #105470):

So #105742 is resolved by #105470; closing this PR as superseded.

One separate note: #105740 (finalizeChunk mutating ColumnAggregateFunction columns still aliased by downstream transforms, sanitizer-only) is a distinct, broader root cause that neither #105470 nor this PR fully addresses. I'll keep it as its own open item rather than fold it in here.

@qoega heads-up since you assigned the original directive.

@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as superseded by #105470 (merged), which fixes #105742 at the source (AggregateFunctionOrFill State-path src reset) without the per-path overhead of this change. See above for verification on master 26.6.1.338.

@groeneai groeneai closed this Jun 2, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…combinator UAF)

Same convertToValues root cause as ClickHouse#105742, manifesting via TotalsHavingTransform
instead of RollupTransform / MergeSorter, and across additional State combinators
(singleValueOrNullState, argMaxState). The fix in ClickHouse#105749 already addresses this
because it patches the upstream `ColumnAggregateFunction::convertToValues` call
site that every finalizeChunk caller (CubeTransform, RollupTransform,
TotalsHavingTransform, AggregatingInOrderTransform) routes through.

Verified pre-fix UBSan fires at UniquesHashSet.h:453 on the CUBE variant
(`runtime error: load of null pointer of type 'HashValue'`); post-fix the test
passes on both Debug and ASan builds.

Closes ClickHouse#105740. Should also close the chronic jemalloc heap-corruption family
issue ClickHouse#102460 since ClickHouse#105740 is its identified upstream root cause.
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

5 participants