Repository navigation
Fix crash in APPLY with aggregate functions and group_by_use_nulls - #101062
alexey-milovidov merged 6 commits into
Conversation
|
cc @novikd @vdimir — could you review this? It fixes a server crash (Bad cast from ColumnVector to ColumnNullable) when using |
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 masterb) Root cause explained? ✅ c) Fix matches root cause? ✅ d) Test intent preserved / New tests added? ✅ e) Both directions demonstrated? ✅
|
|
Workflow [PR], commit [f5be122] Summary: ✅ AI ReviewSummaryThis PR fixes incorrect nullability handling for ClickHouse Rules
Final VerdictStatus: ✅ Approve |
| if (apply->getApplyTransformerType() == ApplyColumnTransformerType::LAMBDA) | ||
| { | ||
| if (const auto * lambda = apply->getExpressionNode()->as<LambdaNode>()) | ||
| if (const auto * func = lambda->getExpression()->as<FunctionNode>()) |
There was a problem hiding this comment.
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.
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]>
4d1bcc4 to
df00ca4
Compare
|
@pufit Good catch — the original code only checked the top-level function in the APPLY lambda. Queries like Fix: Replaced the top-level-only check with a recursive traversal ( Added test cases:
Both crashed on master, both pass with the fix. 50/50 passes with full randomization. |
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%:
b) Root cause explained? ✅ With 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). |
|
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; |
There was a problem hiding this comment.
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.
|
@groeneai, update the branch in this PR. |
…-group-by-use-nulls
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.
|
@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 Root cause of the additional gap: Fix: in commit Pre-PR validation:
Session: cron:clickhouse-ci-task-worker:20260501-164500 |
… 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.
|
@groeneai, update the branch in this PR. |
…-group-by-use-nulls
|
@novikd — rebased onto current master at Verification (debug build, clang-21):
Ready for merge once CI is green. cc @alexey-milovidov (your earlier "update the branch" directive is also addressed). |
LLVM Coverage Report
Changed lines: 97.22% (35/36) · Uncovered code |
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
|
Hi — could this be a backport candidate for Affected code: 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 |
Linked issues
Changelog category (leave one):
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
* APPLYwith aggregate functions andgroup_by_use_nulls=1with GROUPING SETS, ROLLUP, or CUBE.Documentation entry for user-facing changes
What the bug was:
Using
* APPLY x -> argMax(x, number)(or any aggregate function via APPLY lambda) withgroup_by_use_nulls=1andGROUP BY ... WITH ROLLUP/CUBEorGROUPING SETScrashed the server:Root cause:
When the Analyzer resolves
* APPLY x -> argMax(x, number)withgroup_by_use_nulls=1:*matcher expands to the table columns (e.g.,number)group_by_use_nullsis active, matched GROUP BY key columns are converted to Nullable (QueryAnalyzer.cpp line 2165-2176) before APPLY processingx, creatingargMax(Nullable(UInt64), UInt64)AggregateFunctionNullVariadicwithis_nullable[0] = trueUInt64(non-Nullable) — the Nullable wrapping happens post-aggregation in the Rollup/Cube/GroupingSets transformAggregateFunctionNullVariadic::addBatchSinglePlacecallsassert_cast<ColumnNullable>on aColumnVector<UInt64>→ crashIn 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:
Closes #100450
Version info
26.5.1.653