Repository navigation
Conversation
…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.
|
Pre-PR validation gate (TASK.md Phase 4 step 9): a) Deterministic repro: yes - 5-line query from #105742 SEGVs on master b) Root cause explained: yes. c) Fix matches root cause: yes. d) Test intent preserved + new tests added: yes. e) Demonstrated in both directions: yes. Verified by stashing the fix, rebuilding ASan, and running the new test - UBSan fires at f) Fix is general: yes. The fix is at the convertToValues call site, not at the symptom site. All State combinators ( Session: cron:clickhouse-ci-task-worker:20260524-194500 |
|
cc @alexey-milovidov @rschu1ze @KochetovNicolai - could you review? This fixes a server SEGV in any |
…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.
|
Workflow [PR], commit [f0dbe2f] Summary: ❌
AI ReviewSummaryThis PR changes Final Verdict
|
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.
|
Pushed Root cause of the validation failure (not the original bug): the
Fix: run the same queries via Locally verified on master HEAD (no fix): both tests fail with |
LLVM Coverage Report
Changed lines: 100.00% (5/5) · Uncovered code |
…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.
|
@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. |
|
@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 |
… 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.
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. |
|
Closes #105742 |
|
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? |
|
@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 Verified on current master
So #105742 is resolved by #105470; closing this PR as superseded. One separate note: #105740 ( @qoega heads-up since you assigned the original directive. |
…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.
Issue #105742, also fixes #105740 (and root cause of chronic #102460).
Stack on master (
840494d51c9):Reproducer (5 lines after creating the source tables from the issue):
Root cause
ColumnAggregateFunction::convertToValuescallsfunc->insertResultIntofor each row in the source column. For State combinators (e.g.AggregateFunctionState::insertResultInto) this path is optimized to push the source state pointer intores.datawithout copying, relying onres.srcto keep the source column alive.uniqStateOrDefaultisAggregateFunctionOrFill<false>aroundAggregateFunctionState(AggregateFunctionUniq).OrFill::insertResultIntoImplhas two branches:nested_function->insertResultInto->State::insertResultInto-> pushesplacedirectly.to.insertDefault().ColumnAggregateFunction::insertDefaultcallsensureOwnershipfirst, andensureOwnershipalways finishes withsrc.reset(). So once a single flag=0 row is processed,res.srcis null. Any subsequent flag=1 row still pushes a raw pointer intores.data, butresno longer holds a reference to the source column. WhenconvertToValuesreturns and the source column gets destructed, the source column's destructor callsfunc->destroyon every state in itsdata, and those destructors zero out internal pointers (foruniq,UniquesHashSet::~UniquesHashSet -> free()setsbuf = nullptr, whilem_sizeis unchanged at its last value, e.g. 33).Sorting then read those pointers (
MergeSortingTransform -> insertRangeFrom -> ensureOwnership -> IAggregateFunction::merge) and dereferenced the destructed state, segfaulting atUniquesHashSet.h:453(rhs.buf[i]).Relation to #105740 / #102460
convertToValuesis the call path behind everyfinalizeChunk(chunk, mask)(it walks each masked column and replaces it withconvertToValues(...)). 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
insertMergeResultIntoinconvertToValuesinstead ofinsertResultInto. For State combinators (State,OrFill,Null,Resample,ForEach, ...)insertMergeResultIntoforces a real copy viato.insertFrom(place), so every entry inres.dataends up owned byres. For non-State aggregate functions the defaultIAggregateFunction::insertMergeResultIntojust delegates toinsertResultInto, so behavior is unchanged for them.Tests
04275_105742_uniq_state_or_default_rollup_order_by.sql-WITH ROLLUP,WITH ROLLUP WITH TOTALS,WITH CUBE, bareuniqState, each followed byORDER BY. Pre-fix: UBSan null pointer load atUniquesHashSet.h:453. Post-fix: clean.04276_105740_finalize_chunk_state_combinator.sql- the MSan producer fromDB::finalizeChunkmutatesColumnAggregateFunctioncolumns while still aliased by downstream stages / threads — root cause for #102460 (caught by TSan / ASan / MSan) #105740 (singleValueOrNullStateOrDefault+ RIGHT JOIN +WITH TOTALS+ORDER BY) plusuniqStateOrDefaultandargMaxStateOrDefaultvariants covering theTotalsHavingTransformandCubeTransformpaths. Pre-fix: UBSan null pointer load atUniquesHashSet.h:453on the CUBE variant. Post-fix: clean on both Debug and ASan.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
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix server crash and use-after-free in
ColumnAggregateFunction::convertToValueswhen materializing a-Stateaggregate column fromWITH ROLLUP,WITH CUBEorWITH TOTALSfollowed byORDER BY. The crash manifested as a NULL dereference inUniquesHashSet::merge(foruniq*State) or sanitizer use-after-free / use-of-uninitialized (for other State combinators such assingleValueOrNullStateandargMaxState).Closes #105742