Skip to content

Fix crash in APPLY with aggregate functions and group_by_use_nulls - #101062

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-apply-aggregate-group-by-use-nulls
May 14, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-apply-aggregate-group-by-use-nulls

Conversation

@groeneai

@groeneai groeneai commented Mar 29, 2026 •

Copy link
Copy Markdown
Collaborator

Linked issues

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

Fixed server crash (Logical error: Bad cast from ColumnVector to ColumnNullable) when using * APPLY with aggregate functions and group_by_use_nulls=1 with GROUPING SETS, ROLLUP, or CUBE.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

What the bug was:

Using * APPLY x -> argMax(x, number) (or any aggregate function via APPLY lambda) with group_by_use_nulls=1 and GROUP BY ... WITH ROLLUP/CUBE or GROUPING SETS crashed the server:

Logical error: 'Bad cast from type DB::ColumnVector<unsigned long> to DB::ColumnNullable'

Root cause:

When the Analyzer resolves * APPLY x -> argMax(x, number) with group_by_use_nulls=1:

  1. The * matcher expands to the table columns (e.g., number)
  2. Since group_by_use_nulls is active, matched GROUP BY key columns are converted to Nullable (QueryAnalyzer.cpp line 2165-2176) before APPLY processing
  3. The APPLY lambda binds the Nullable column to x, creating argMax(Nullable(UInt64), UInt64)
  4. The aggregate function factory creates AggregateFunctionNullVariadic with is_nullable[0] = true
  5. But the actual input column to the Aggregating step is UInt64 (non-Nullable) — the Nullable wrapping happens post-aggregation in the Rollup/Cube/GroupingSets transform
  6. At runtime, AggregateFunctionNullVariadic::addBatchSinglePlace calls assert_cast<ColumnNullable> on a ColumnVector<UInt64> → crash

In the working case (SELECT argMax(number, number) ... GROUP BY GROUPING SETS (...) without APPLY), both arguments are resolved inside the aggregate function scope where Nullable conversion is correctly skipped. The APPLY code path bypasses this because the conversion happens before the lambda is resolved.

Fix:

Before the Nullable conversion of matched nodes, check whether the APPLY transformer will create an aggregate function (by checking AggregateFunctionFactory::isAggregateFunctionName() on the lambda body or function name). If so, skip the Nullable conversion — aggregate function arguments should use pre-aggregation types. The Planner's Rollup/Cube/GroupingSets transforms handle the Nullable wrapping post-aggregation.

Reproduction:

SET group_by_use_nulls = 1;
SELECT * APPLY x -> argMax(x, number) FROM numbers(1) GROUP BY number WITH ROLLUP; -- crashes
SELECT * APPLY x -> argMax(x, number) FROM numbers(1) GROUP BY GROUPING SETS ((materialize(65537)), (*)); -- crashes

Closes #100450

Version info

  • Merged into: 26.5.1.653

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review this? It fixes a server crash (Bad cast from ColumnVector to ColumnNullable) when using * APPLY x -> aggregate(x, ...) with group_by_use_nulls=1 and GROUPING SETS/ROLLUP/CUBE. The root cause was in QueryAnalyzer's matcher resolution which converted matched GROUP BY key columns to Nullable before APPLY lambda resolution, causing a type mismatch in the Aggregating step.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session: cron:clickhouse-ci-task-worker:20260329-051500)

a) Deterministic repro? ✅

SET group_by_use_nulls=1;
SELECT * APPLY x -> argMax(x, number) FROM numbers(1) GROUP BY number WITH ROLLUP;
-- Crashes 100% on unpatched master

b) Root cause explained? ✅
With group_by_use_nulls=1, the Analyzer's matcher resolution (QueryAnalyzer.cpp:2165-2176) converts matched GROUP BY key columns to Nullable before APPLY processing. When the APPLY lambda creates argMax(x, number), the lambda parameter x is already Nullable, producing argMax(Nullable(UInt64), UInt64). The factory creates AggregateFunctionNullVariadic with is_nullable[0]=true. But the Aggregating step receives non-Nullable UInt64 columns — Nullable wrapping happens post-aggregation in Rollup/GroupingSets transforms. The type mismatch causes assert_cast<ColumnNullable> to crash on ColumnVector<UInt64>.

c) Fix matches root cause? ✅
The fix detects APPLY transformers containing aggregate functions (via isAggregateFunctionName) and skips the premature Nullable conversion. This matches how direct aggregate function arguments are handled (lines 3138-3154 in the same file — Nullable conversion is skipped inside aggregate function scope).

d) Test intent preserved / New tests added? ✅
Created 04067_group_by_use_nulls_apply_aggregate.sql with 6 test cases: GROUPING SETS, ROLLUP, CUBE, multi-column, sum aggregate, and non-aggregate APPLY (verifying Nullable still works for non-aggregate cases). All existing group_by_use_nulls and grouping_sets tests pass (11/11 local, 3 distributed-only tests correctly skipped).

e) Both directions demonstrated? ✅

  • Without fix: crash on every execution (confirmed with 5 variants)
  • With fix: 50/50 passes with full randomization (--test-runs 50)

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f5be122]

Summary: ✅


AI Review

Summary

This PR fixes incorrect nullability handling for * APPLY with aggregate functions under group_by_use_nulls=1 and adds targeted stateless coverage for LAMBDA, nested aggregate expressions, and function-form APPLY. I did not find new correctness, safety, or performance issues in the final diff.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 29, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Outdated
if (apply->getApplyTransformerType() == ApplyColumnTransformerType::LAMBDA)
{
if (const auto * lambda = apply->getExpressionNode()->as<LambdaNode>())
if (const auto * func = lambda->getExpression()->as<FunctionNode>())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This aggregate detection only checks whether the top-level lambda expression is a FunctionNode whose name is aggregate. That misses cases like * APPLY x -> toString(argMax(x, number)) (or any aggregate nested below another function), so has_aggregate_apply_transformer stays false and the nullable conversion below still runs.

In those cases we still build aggregate states from non-nullable pre-aggregation columns, so this can reproduce the same ColumnVector vs ColumnNullable mismatch path.

Please use subtree detection instead of top-level-name detection, e.g. hasAggregateFunctionNodes(lambda->getExpression()) (or equivalent for the function transformer expression), so any nested aggregate inside the APPLY expression disables this nullable conversion.

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 check this

When using `* APPLY x -> argMax(x, ...)` with `group_by_use_nulls=1`
and GROUPING SETS/ROLLUP/CUBE, the server crashed with:

  Logical error: Bad cast from type DB::ColumnVector<unsigned long>
  to DB::ColumnNullable

Root cause: The Analyzer's matcher resolution converted matched GROUP BY
key columns to Nullable before passing them as APPLY lambda arguments.
This caused the aggregate function to be created with Nullable argument
types (via AggregateFunctionNullVariadic), but the actual input columns
to the Aggregating step are non-Nullable — the Nullable wrapping happens
post-aggregation in Rollup/Cube/GroupingSets transforms.

Fix: Skip the premature Nullable conversion when the APPLY transformer
will create an aggregate function. Aggregate function arguments should
use pre-aggregation types. The post-aggregation Nullable wrapping is
handled by the Planner's Rollup/Cube/GroupingSets transforms.

Closes ClickHouse#100450

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai
groeneai force-pushed the fix-apply-aggregate-group-by-use-nulls branch from 4d1bcc4 to df00ca4 Compare March 30, 2026 15:30
@groeneai

Copy link
Copy Markdown
Collaborator Author

@pufit Good catch — the original code only checked the top-level function in the APPLY lambda. Queries like * APPLY x -> toString(argMax(x, number)) would still crash because toString is not an aggregate, so the check missed the nested argMax.

Fix: Replaced the top-level-only check with a recursive traversal (has_aggregate_function_in_tree) that walks the entire APPLY expression tree and checks each FunctionNode against AggregateFunctionFactory::isAggregateFunctionName(). We use the factory name lookup rather than FunctionNode::isAggregateFunction() because APPLY expressions haven't been resolved at this point (FunctionNode::kind is still UNKNOWN).

Added test cases:

  • * APPLY x -> toString(argMax(x, number)) — aggregate nested inside another function
  • * APPLY x -> length(toString(sum(x))) — deeply nested aggregate

Both crashed on master, both pass with the fix. 50/50 passes with full randomization.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (updated fix — session cron:clickhouse-ci-task-worker:20260330-151500)

a) Deterministic repro? ✅ Yes — both the original and new crash cases reproduce 100%:

  • SET group_by_use_nulls=1; SELECT * APPLY x -> argMax(x, number) FROM numbers(1) GROUP BY GROUPING SETS ((materialize(65537)), (*)) — crashes (top-level aggregate)
  • SET group_by_use_nulls=1; SELECT * APPLY x -> toString(argMax(x, number)) FROM numbers(1) GROUP BY GROUPING SETS ((materialize(65537)), (*)) — crashes (nested aggregate, new case)

b) Root cause explained? ✅ With group_by_use_nulls=1 and ROLLUP/CUBE/GROUPING SETS, resolveMatcher() converts matched GROUP BY key columns to Nullable before APPLY processing. When APPLY creates an aggregate function (directly or nested inside other functions), the aggregate expects non-Nullable pre-aggregation column types. The Nullable wrapping happens post-aggregation. Converting columns to Nullable before APPLY causes AggregateFunctionNullVariadic to receive a type it doesn't expect → "Bad cast from ColumnVector to ColumnNullable".

c) Fix matches root cause? ✅ The fix recursively checks the APPLY expression tree for aggregate functions (using factory name lookup since nodes are unresolved) and skips the Nullable conversion when any aggregate is found, regardless of nesting depth. This directly addresses the type mismatch mechanism.

d) Test intent preserved / new tests added? ✅ Added 2 new test cases for nested aggregates. Existing non-aggregate APPLY test still verifies Nullable output is produced correctly (the fix only skips conversion when aggregates are present).

e) Both directions? ✅ On master binary: all 3 crash queries (top-level, nested, deeply nested) crash. With fix: all pass. 50/50 with full randomization. 10 related group_by_use_nulls and APPLY tests all pass (0 regressions).

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

SELECT * APPLY x -> length(toString(sum(x))) FROM numbers(3) GROUP BY number WITH ROLLUP ORDER BY number;

-- Non-aggregate APPLY should still produce Nullable output
SELECT * APPLY toString FROM (SELECT number FROM numbers(2)) GROUP BY number WITH ROLLUP ORDER BY number;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice coverage for lambda APPLY paths. One gap remains: this patch also adds ApplyColumnTransformerType::FUNCTION detection (expr_to_check = apply->getExpressionNode().get()), but the new regression tests only exercise aggregate detection through lambda (x -> sum(x) / nested lambda) and non-aggregate function (APPLY toString).

Please add a group_by_use_nulls = 1 case for function-form aggregate, for example:
SELECT * APPLY sum FROM numbers(3) GROUP BY number WITH ROLLUP ORDER BY number;

That would directly verify the FUNCTION branch against the same Nullable/non-Nullable mismatch class this PR fixes.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, update the branch in this PR.

groeneai added 2 commits May 1, 2026 16:48
Addresses bot review feedback on PR ClickHouse#101062: the previous patch added a
detection branch for `ApplyColumnTransformerType::FUNCTION` in
`resolveMatcher`, but the only regression test that exercises FUNCTION-form
APPLY uses a non-aggregate function (`* APPLY toString`). The FUNCTION-form
aggregate variant (e.g. `* APPLY sum`) still crashed with the same
`Bad cast from ColumnVector to ColumnNullable` because of a second Nullable
conversion site in `resolveExpressionNode` (gated by `in_aggregate_function_scope`).

Root cause: `resolveMatcher` calls `resolveFunction` directly for the
FUNCTION-form APPLY branch, while the LAMBDA branch goes through
`resolveLambda` -> `resolveExpressionNode`, which pushes the aggregate
function onto the resolve stack before resolving its arguments. Without
that push, when the matched column appended as an argument is later
resolved, `expressions_in_resolve_process_stack.hasAggregateFunction()`
returns `false`, so `resolveExpressionNode` converts the column to Nullable
(line ~3231). The aggregate function is then created with Nullable input
types but receives non-Nullable columns at runtime, triggering the bad cast
in `AggregateFunctionNullUnary::add`.

Fix: push the cloned function onto the resolve stack around the
`resolveFunction` call in the FUNCTION-form APPLY branch, then pop after.
This makes argument resolution see the aggregate context, matching the
LAMBDA branch behaviour.

Test: added `* APPLY sum FROM numbers(3) GROUP BY number WITH ROLLUP`
to the existing regression test. Verified locally: the new query
deterministically aborts the server without this change and passes 50/50
with random settings after the change.
@groeneai

groeneai commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov rebased onto current master via merge (per CLAUDE.md "do not use rebase or amend").

@clickhouse-gh[bot] thanks for the catch — adding the * APPLY sum test exposed a real gap in the previous patch, not just a coverage hole. The FUNCTION-form aggregate test deterministically aborted the server with the same Bad cast from type DB::IColumn const* to DB::ColumnNullable const*, even though all LAMBDA-form aggregate tests passed.

Root cause of the additional gap: resolveMatcher calls resolveFunction directly for the FUNCTION-form APPLY branch, whereas the LAMBDA branch goes through resolveLambda -> resolveExpressionNode. The latter pushes the function onto expressions_in_resolve_process_stack (at QueryAnalyzer.cpp:2884) before resolving arguments, which is exactly what the second Nullable-conversion gate (in_aggregate_function_scope, lines ~3214-3239) reads. Without that push, the matched column appended as an argument is converted to Nullable in the second site even though the first site (with the has_aggregate_apply_transformer check) correctly skipped it. The aggregate function is then created with Nullable(UInt64) input but receives non-Nullable columns at runtime — bad cast in AggregateFunctionNullUnary::add.

Fix: in commit 1796ac8 I push the cloned function onto the resolve stack around the resolveFunction call in the FUNCTION-form APPLY branch and pop after. This makes argument resolution see the aggregate context, matching how the LAMBDA branch behaves.

Pre-PR validation:

  • a) Deterministic repro: SET group_by_use_nulls = 1; SELECT * APPLY sum FROM numbers(3) GROUP BY number WITH ROLLUP ORDER BY number; aborts the server without the fix on every run.
  • b) Root cause explained: see above (two Nullable-conversion sites; LAMBDA branch already handles the second via implicit push from resolveExpressionNode; FUNCTION branch was missing the push).
  • c) Fix matches root cause: the smallest possible change — push/pop the function around the existing resolveFunction call. No conversion logic is altered; only the stack is told what scope we are in.
  • d) Test intent preserved: existing tests still pass (50/50 with random settings); the new case is a new test row, not a relaxation.
  • e) Both directions demonstrated: server aborts on every run before commit 1796ac8; passes 50/50 after.

Session: cron:clickhouse-ci-task-worker:20260501-164500

@novikd novikd self-assigned this May 4, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
… walk

Per @novikd review feedback on PR ClickHouse#101062: replace the
`has_aggregate_function_in_tree(self, node)` recursive lambda with an
iterative `while`-loop traversal using a worklist/stack pattern, matching
the canonical style used in `src/Analyzer/Utils.cpp` (`isNodePartOfTree`,
`isStorageUsedInTree`).

No behavior change: same nodes visited, same termination on the first
aggregate `FunctionNode` encountered. Only the traversal mechanism changes
(explicit `std::vector` worklist instead of self-propagation through the
lambda parameter).

Verified locally: 50/50 randomized runs of
`04067_group_by_use_nulls_apply_aggregate` pass; all 11 APPLY-related
stateless tests pass.

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

LGTM

@novikd

novikd commented May 7, 2026

Copy link
Copy Markdown
Member

@groeneai, update the branch in this PR.

@groeneai

groeneai commented May 7, 2026

Copy link
Copy Markdown
Collaborator Author

@novikd — rebased onto current master at f5be122cac7617909747dd6e3e5be14a7543283e (merge of origin/master into the PR branch — no force-push, preserving review history per repo conventions).

Verification (debug build, clang-21):

  • 04067_group_by_use_nulls_apply_aggregate: 50/50 passes with full settings randomization (--test-runs 50).
  • All 11 APPLY-related stateless tests pass on a single run.
  • The fix's two halves (recursive aggregate detection in resolveMatcher, push/pop around resolveFunction for the FUNCTION-form APPLY branch) are preserved verbatim through the merge — confirmed by git diff origin/master HEAD -- src/Analyzer/Resolve/QueryAnalyzer.cpp.

Ready for merge once CI is green. cc @alexey-milovidov (your earlier "update the branch" directive is also addressed).

@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.10% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.70% 76.60% -0.10%

Changed lines: 97.22% (35/36) · Uncovered code

Full report · Diff report

groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 12, 2026
Master AST fuzzer hit `Segmentation fault (STID: 0988-2212)` on
`AST fuzzer (amd_msan)` for `groupArrayMovingSum` on PR ClickHouse#100394
and on `AST fuzzer (arm_asan_ubsan)` / `amd_debug` for PRs ClickHouse#101033,
ClickHouse#101062, ClickHouse#104531 — same bug class as STID 0988-40af / 0988-3351.
The fuzzer mutated a query into `groupArrayMovingSumState(...) * N`,
which goes through `FunctionBinaryArithmetic::executeAggregateMultiply`.
The exponentiation-by-squaring loop called
`function->merge(vec_from[i], vec_from[i], arena.get())`, and
`MovingImpl::merge` then did
`cur_elems.value.insert(rhs_elems.value.begin(), rhs_elems.value.end(), arena)`
where `rhs_elems` aliased `cur_elems.value`, so the source iterators
referenced the buffer that `insertPrepare` was about to reallocate.

The fix in this PR (copy `vec_from` into an independent column before
each squaring step) eliminates the self-alias at the call site, so
`MovingImpl::merge` is never invoked with `place == rhs` from
`executeAggregateMultiply` anymore.

The new test exercises every `MovingImpl` instantiation reachable from
`groupArrayMovingSum` / `groupArrayMovingAvg`:
  - integer accumulator,
  - decimal accumulator (the variant flagged on PR ClickHouse#101062),
  - windowed parameterisation (`LimitNumElements::value = true`),
  - the `agg_state_is_const` path through `arrayJoin([state, state])`.

Verified locally on Debug build that pre-fix the squaring path aborts
with the PODArray `assertNotIntersects` assertion (Server `<Fatal>`),
while `state * 1` (no squaring branch) returns `50` — matching the
single-state baseline used to derive the reference values.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100394&sha=7309f23dc7ccee494b41416c8fff18c02d0697a7&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 14, 2026
Merged via the queue into ClickHouse:master with commit 3eec25d May 14, 2026
165 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: QueryAnalyzer::resolveMatcher in src/Analyzer/Resolve/QueryAnalyzer.cpp - nullable group by key handling with APPLY transformers — core code present in all supported branches.

Why this might apply: This PR fixes a crash (Segmentation fault) that occurs with a valid SQL query using APPLY with aggregate functions and group_by_use_nulls=1. The affected code path in QueryAnalyzer::resolveMatcher has existed since the analyzer was introduced. The crash is triggered by common SQL patterns (GROUP BY ... WITH ROLLUP/CUBE or GROUPING SETS).

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

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

Logical error: Bad cast from type A to B (STID: 3520-43e0)

6 participants