Skip to content

Fix exception in correlated subquery with group_by_use_nulls + ROLLUP/CUBE - #100365

Merged
alexey-milovidov merged 60 commits into
masterfrom
fix-correlated-subquery-group-by-use-nulls
Jul 12, 2026
Merged

alexey-milovidov merged 60 commits into
masterfrom
fix-correlated-subquery-group-by-use-nulls

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

When a correlated subquery references an outer column that becomes Nullable due to group_by_use_nulls with ROLLUP/CUBE, the analyzer was binding inner expressions, factory functions, and aggregate functions with the pre-Nullable type. 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 the Nullable-wrapped columns. At runtime the function produced a Nullable result but the DAG expected the non-Nullable type, causing exceptions such as Unexpected 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 right nullable_group_by_keys, and 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 rather than 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:

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

The previous band-aid (ActionsDAG::reconcileInputTypesAfterDecorrelation and an aggregate function rebuild loop in decorrelateQueryPlan's AggregatingStep branch) is removed, along with Aggregator::Params::cloneWithKeysAndAggregates which only existed to support that loop. Aggregator::Params::cloneWithKeys is now const-qualified so a fresh Params can be derived from a const reference without const_cast.

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 an exception in correlated subqueries when outer columns become Nullable under group_by_use_nulls with ROLLUP/CUBE.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.811 (included in 26.7 and later)

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1e38b67]

Summary: ✅


AI Review

Summary

This PR moves the group_by_use_nulls nullability fix for correlated subqueries into the analyzer and removes the later ActionsDAG / AggregatingStep repair path. The current implementation addresses the earlier source-scope and only_merge issues, but the review is still not at approval because the regression file does not yet prove the previously identified higher-order / lambda-capture path.

Tests
  • ⚠️ [tests/queries/0_stateless/04053_correlated_subquery_group_by_use_nulls.sql:18] Please add one focused case where the correlated outer column is captured inside a lambda or higher-order function under group_by_use_nulls with ROLLUP or CUBE. The old failure mode around FunctionCapture was concrete, and this PR removes the downstream repair logic entirely, so that shape still needs direct regression coverage.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: add a focused regression test for the higher-order / lambda-capture correlated-subquery path.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Mar 22, 2026
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
alexey-milovidov and others added 4 commits March 24, 2026 00:31
…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]>
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
SELECT number, (SELECT number + 1), sum(number) AS val
FROM numbers(5)
GROUP BY number
WITH CUBE

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.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

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.

Comment thread src/Interpreters/ActionsDAG.cpp Resolved
alexey-milovidov and others added 7 commits April 9, 2026 12:40
…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]>
…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]>
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
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.
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
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 alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Finally a good fix of the root cause!

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review July 12, 2026 00:16
@alexey-milovidov alexey-milovidov self-assigned this Jul 12, 2026
@alexey-milovidov
alexey-milovidov merged commit 8b6d09c into master Jul 12, 2026
173 of 174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-correlated-subquery-group-by-use-nulls branch July 12, 2026 00:16
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 12, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Jul 14, 2026
…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]>
alexey-milovidov pushed a commit to remogeissbuehler/ClickHouse that referenced this pull request Jul 14, 2026
…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]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Jul 15, 2026
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]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Jul 19, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ubquery-group-by-use-nulls

Fix exception in correlated subquery with `group_by_use_nulls` + ROLLUP/CUBE
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants