Repository navigation
Fix exception in correlated subquery with group_by_use_nulls + ROLLUP/CUBE - #100365
Conversation
…UP/CUBE When a correlated subquery references an outer column that becomes Nullable due to `group_by_use_nulls` with ROLLUP/CUBE, the inner expression DAG's function nodes were built with pre-Nullable types during analysis. During decorrelation, PLACEHOLDER nodes became INPUT nodes but kept their original types, while the actual input from the CROSS JOIN carried the Nullable-wrapped columns. At runtime, the function produced a Nullable result but the DAG expected the original non-Nullable type, causing: "Unexpected return type from modulo. Expected UInt8. Got Nullable(UInt8)." The fix adds `ActionsDAG::reconcileInputTypesAfterDecorrelation` which, after decorrelation, updates INPUT node types to match the actual input header and rebuilds any dependent FUNCTION nodes whose argument types changed. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [1e38b67] Summary: ✅
AI ReviewSummaryThis PR moves the Tests
Final Verdict
|
…uery-group-by-use-nulls # Conflicts: # src/Interpreters/ActionsDAG.cpp
…fterDecorrelation` When `FunctionFactory::tryGet` cannot resolve a function name after detecting a type mismatch, throw a `LOGICAL_ERROR` instead of silently skipping the rebuild. This prevents stale `result_type` / `function` for non-factory function nodes (e.g. `FunctionCapture`). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| SELECT number, (SELECT number + 1), sum(number) AS val | ||
| FROM numbers(5) | ||
| GROUP BY number | ||
| WITH CUBE |
There was a problem hiding this comment.
The new regression covers %/+ with group_by_use_nulls + ROLLUP/CUBE, but it does not cover the higher-order/lambda capture path. Please add a case where a correlated expression includes a lambda/capture over an outer column in the same nullable-shape scenario.
Without that, reconcileInputTypesAfterDecorrelation changes around non-factory function nodes can regress without test signal.
|
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. |
…uery-group-by-use-nulls
…g, extend tests For non-factory function nodes (e.g. `FunctionCapture` built for lambda captures), the previous code threw `LOGICAL_ERROR` on type mismatch. Such scenarios are pre-existing limitations outside the scope of this fix; replace the throw with `continue` so the behavior matches master for non-factory functions instead of regressing with a new exception. After rebuilding a `FUNCTION` node, invalidate `node.column` (the cached constant-folding result) and recompute it the same way `addFunctionImpl` does. The old column was computed under the previous signature (for example, non-Nullable arguments) and may no longer be valid. Extend the regression test to exercise the `FilterStep` reconciliation path (a correlated subquery inside `HAVING` and inside `WHERE` under `group_by_use_nulls` + ROLLUP), not just `ExpressionStep` projections. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e_nulls` + ROLLUP The previous tests covered the factory-function path (`%`, `+`) of `reconcileInputTypesAfterDecorrelation`. Add a test for the non-factory function path that triggers `FunctionCapture` for a lambda capturing an outer column. `FunctionCapture` is not registered in `FunctionFactory` and is therefore skipped by the reconciler. The query currently fails with a clear `LOGICAL_ERROR` from `FunctionCapture::executeImpl` (the same behavior as on master), documenting that this scenario is a pre-existing limitation outside the scope of this fix. The test also pins the `continue` branch of the reconciler: a regression that throws "Cannot rebuild function" instead of forwarding to the `FunctionCapture` execution-time error would still surface as `LOGICAL_ERROR`, but the error context (`FunctionCapture` vs. `ActionsDAG`) makes the difference easy to investigate from CI logs. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…uery-group-by-use-nulls
…uery-group-by-use-nulls
…anitizer builds
`LOGICAL_ERROR` calls `abort()` when the server is built with a debug
or sanitizer configuration (see `abortOnFailedAssertion` in
`src/Common/Exception.cpp`). A test that expects `LOGICAL_ERROR` via
`-- { serverError LOGICAL_ERROR }` therefore passes only in release
builds and fails under the debug / ASan / UBSan / TSan / MSan CI
variants (the server aborts, the client sees a broken connection
instead of the expected error code).
The removed query documented a pre-existing limitation of
`FunctionCapture` (lambda captures cannot be rebuilt after the captured
column is wrapped in `Nullable` by `group_by_use_nulls` + ROLLUP). That
limitation is outside the scope of this PR, and the test did not pin
any behavior introduced here: the `continue` branch in
`reconcileInputTypesAfterDecorrelation` is already exercised by the
other queries in this file whenever a non-factory function happens to
appear in a decorrelated expression. Guarding the limitation with
many `no-debug, no-tsan, no-asan, no-msan, no-ubsan` tags is not
justified for a documentation-only case.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…uery-group-by-use-nulls
…uery-group-by-use-nulls
When `reconcileInputTypesAfterDecorrelation` rebuilds a `FUNCTION` node, any `ALIAS` node above it inherited the old `child.column` from `createAlias`. Updating only `result_type` left a stale constant that later consumers (e.g. `ActionsDAG` serialization via `serializeConstant`) could observe with a type mismatch. Refresh `node.column` from the child whenever the alias's `result_type` is updated.
…uery-group-by-use-nulls
Aliases mirror their child's `result_type` and `column`. The previous guard refreshed them only when `result_type` differed, but a child `FUNCTION` rebuilt above can keep the same `result_type` while having its `column` recomputed (or cleared) - leaving the alias with a stale constant that would later be used by consumers such as `ActionsDAG` serialization (`serializeConstant`).
alexey-milovidov
left a comment
There was a problem hiding this comment.
Finally a good fix of the root cause!
…ith group_by_use_nulls Covers the execution-time variant of the group_by_use_nulls + ROLLUP/CUBE correlated-subquery family (bad cast ColumnNullable -> ColumnVector in AggregateFunctionDistinct::add), fixed at the analyzer level by ClickHouse#100365. The test asserts correct results, which also guards the release-build path where the cast silently reinterprets the column instead of aborting. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…roup_by_use_nulls Issue ClickHouse#107445 reported a LOGICAL_ERROR ('Unexpected return type from toString/tuple/toInt64. Expected T. Got Nullable(T)') when a correlated scalar subquery applies a return-type-sensitive function to the outer key under WITH ROLLUP + group_by_use_nulls. The root cause (stale pre-Nullable result type in the decorrelated expression DAG) was fixed by ClickHouse#100365. These are regression guards for the exact reported manifestations, which the ClickHouse#100365 test did not cover explicitly. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Test 04053_correlated_subquery_group_by_use_nulls was added on master by PR ClickHouse#100365 after this branch's previous merge-base. Its first query uses GROUP BY ... WITH ROLLUP WITH TOTALS under group_by_use_nulls = 1, and this PR intentionally reports the GROUP BY keys as NULL in the TOTALS row instead of the default value 0, so the expected TOTALS row changes from "0 \N 45" to "\N \N 45". CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107106&sha=aa903ca1db8bec56709d1212b318c28e763715f0&name_0=PR&name_1=Fast%20test PR: ClickHouse#107106 Co-Authored-By: Claude Fable 5 <[email protected]>
…oup_by_use_nulls The fuzzer query from issue ClickHouse#102273 used to fail with a logical error "Unexpected return type from `bitNot`. Expected UInt64. Got Nullable(UInt64)" because the correlated column kept its pre-Nullable type while the post-aggregation rows carried Nullable values. The bug was fixed in the analyzer by ClickHouse#100365, which covered `WITH ROLLUP` and `WITH CUBE` shapes in test 04053; this adds the `GROUPING SETS` shape. Co-Authored-By: Claude Fable 5 <[email protected]>
…e root cause
The previous commits patched up types after decorrelation by adding
`ActionsDAG::reconcileInputTypesAfterDecorrelation` and an aggregate
function rebuild loop in `decorrelateQueryPlan`'s `AggregatingStep`
branch. As discussed in review, that masked the real problem: the
analyzer was binding inner expressions, factory functions, and
aggregate functions with the pre-`Nullable` type for correlated columns
whose outer references will become `Nullable` due to
`group_by_use_nulls` with ROLLUP/CUBE.
Fix the root cause in `QueryAnalyzer::resolveExpressionNode`: when a
column reference is correlated (its source is in an ancestor scope),
traverse outer scopes to apply the right `nullable_group_by_keys`, and
also bypass the `in_aggregate_function_scope` guard for that case
(an aggregate inside an inner correlated subquery operates on rows
produced by the outer post-aggregation step, where the column is
already `Nullable`).
The correlated column is mutated in place (instead of cloned) so that
the same `ColumnNode` shared between the inner expression and the outer
`QueryNode::correlated_columns_list` stays consistent. The planner's
`correlated_columns_set` is hashed by type, so a clone with a different
type would no longer be recognized as correlated and the inner DAG's
PLACEHOLDER for the correlated column would not be added.
With the analyzer producing the correct types up front, the band-aid
goes away:
- inner DAG INPUT types match the CROSS JOIN input header,
- factory function bindings match argument types,
- aggregate functions inside correlated subqueries are bound with the
right argument types.
Removed `ActionsDAG::reconcileInputTypesAfterDecorrelation` (and its
two call sites) and the aggregate function rebuild loop. Also dropped
`Aggregator::Params::cloneWithKeysAndAggregates` (only used by that
loop) and made `cloneWithKeys` `const`-qualified so a fresh `Params`
can be derived from a `const` reference without a `const_cast`.
CI report (last band-aid revision):
ClickHouse#100365
… scope The previous fix stopped walking past the column-source scope, but it still ran `nullable_group_by_keys.find(node)` at every scope on the way up. `nullable_group_by_keys` is keyed by `QueryTreeNodePtrWithHashIgnoreTypes`, and `ColumnNode::isEqualImpl` compares column nodes by name (ignoring source and types), so a same-named key in an intermediate ancestor scope could match a correlated column whose real source lives further out and wrongly convert the column to `Nullable`. Gate the lookup so that, for correlated columns, `nullable_group_by_keys` is consulted only at the source-owning scope: that is the only scope whose `group_by_use_nulls` actually applied to this column. The walk still stops once the source-owning scope is reached. Behavior for non-correlated references is unchanged. Review: ClickHouse#100365 (comment) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ubquery-group-by-use-nulls Fix exception in correlated subquery with `group_by_use_nulls` + ROLLUP/CUBE
…ith group_by_use_nulls Covers the execution-time variant of the group_by_use_nulls + ROLLUP/CUBE correlated-subquery family (bad cast ColumnNullable -> ColumnVector in AggregateFunctionDistinct::add), fixed at the analyzer level by ClickHouse#100365. The test asserts correct results, which also guards the release-build path where the cast silently reinterprets the column instead of aborting. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…roup_by_use_nulls Issue ClickHouse#107445 reported a LOGICAL_ERROR ('Unexpected return type from toString/tuple/toInt64. Expected T. Got Nullable(T)') when a correlated scalar subquery applies a return-type-sensitive function to the outer key under WITH ROLLUP + group_by_use_nulls. The root cause (stale pre-Nullable result type in the decorrelated expression DAG) was fixed by ClickHouse#100365. These are regression guards for the exact reported manifestations, which the ClickHouse#100365 test did not cover explicitly. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…oup_by_use_nulls The fuzzer query from issue ClickHouse#102273 used to fail with a logical error "Unexpected return type from `bitNot`. Expected UInt64. Got Nullable(UInt64)" because the correlated column kept its pre-Nullable type while the post-aggregation rows carried Nullable values. The bug was fixed in the analyzer by ClickHouse#100365, which covered `WITH ROLLUP` and `WITH CUBE` shapes in test 04053; this adds the `GROUPING SETS` shape. Co-Authored-By: Claude Fable 5 <[email protected]>
When a correlated subquery references an outer column that becomes
Nullabledue togroup_by_use_nullswith ROLLUP/CUBE, the analyzer was binding inner expressions, factory functions, and aggregate functions with the pre-Nullabletype. During decorrelation, the inner DAG's PLACEHOLDER nodes became INPUT nodes that kept their original (non-Nullable) types, while the actual input from the CROSS JOIN carried theNullable-wrapped columns. At runtime the function produced aNullableresult but the DAG expected the non-Nullabletype, causing exceptions such asUnexpected return type from modulo. Expected UInt8. Got Nullable(UInt8).The fix is in
QueryAnalyzer::resolveExpressionNode: when a column reference is correlated (its source is in an ancestor scope), traverse outer scopes to apply the rightnullable_group_by_keys, and bypass thein_aggregate_function_scopeguard for that case (an aggregate inside an inner correlated subquery operates on rows produced by the outer post-aggregation step, where the column is alreadyNullable).The correlated column is mutated in place rather than cloned so that the same
ColumnNodeshared between the inner expression and the outerQueryNode::correlated_columns_liststays consistent. The planner'scorrelated_columns_setis hashed by type, so a clone with a different type would no longer be recognized as correlated and the inner DAG's PLACEHOLDER for the correlated column would not be added.With the analyzer producing the correct types up front:
INPUTtypes match the CROSS JOIN input header,The previous band-aid (
ActionsDAG::reconcileInputTypesAfterDecorrelationand an aggregate function rebuild loop indecorrelateQueryPlan'sAggregatingStepbranch) is removed, along withAggregator::Params::cloneWithKeysAndAggregateswhich only existed to support that loop.Aggregator::Params::cloneWithKeysis nowconst-qualified so a freshParamscan be derived from aconstreference withoutconst_cast.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed an exception in correlated subqueries when outer columns become
Nullableundergroup_by_use_nullswith ROLLUP/CUBE.Documentation entry for user-facing changes
Version info
26.7.1.811(included in26.7and later)