Skip to content

Fix correlated subquery + GROUP BY ROLLUP under group_by_use_nulls - #104350

Open
groeneai wants to merge 23 commits into
ClickHouse:masterfrom
groeneai:fix-91119-correlated-rollup-cast-wrapper
Open

groeneai wants to merge 23 commits into
ClickHouse:masterfrom
groeneai:fix-91119-correlated-rollup-cast-wrapper

Conversation

@groeneai

@groeneai groeneai commented May 8, 2026 •

Copy link
Copy Markdown
Collaborator

A correlated subquery references an outer column that is a GROUP BY key of an outer query under group_by_use_nulls = 1 with WITH ROLLUP/CUBE/GROUPING SETS. The actual values fed into the inner subquery are post-rollup Nullables, but the analyzer used to leave the inner column reference at its non-Nullable type. The planner then built CAST wrappers and aggregate functions with the original signature, and at header inference (after decorrelation replaced PLACEHOLDER nodes with INPUT nodes of the actual Nullable types) the precomputed wrappers raised Logical error: 'Bad cast from type DB::ColumnNullable to DB::ColumnVector<...>'.

The minimal reproducer from issue #91119 hits createUInt8ToBoolWrapper:

SELECT (SELECT c0)
FROM (SELECT 1::Bool) t0(c0)
GROUP BY c0 WITH ROLLUP
SETTINGS group_by_use_nulls = 1;

The same surface bug class also appears for plain numeric types (modulo, plus), aggregate functions over correlated outer columns (e.g. (SELECT anyLastOrDefault(number))), correlated HAVING/WHERE filter steps, and Nullable source columns.

The root cause is in QueryAnalyzer::resolveExpressionNode: the nullable_group_by_keys walk stops at the first enclosing QUERY scope, so the outer scope where the column was defined is never consulted for an inner correlated reference. This change makes the walk continue past the inner QUERY scope when the node is a column whose source table expression is registered in a deeper outer scope (i.e. the column is correlated). The aggregate-function exclusion is now evaluated against each scope's expressions_in_resolve_process_stack, so an outer scope's nullable_group_by_keys applies even when the inner subquery is currently inside an inner aggregate (the inner aggregate operates on the outer's already-Nullable values).

For correlated matches the existing node is mutated in place instead of being replaced with a clone of the GROUP BY key. The same shared_ptr is referenced by the enclosing QueryNode::correlated_columns list (registered via addCorrelatedColumn); cloning would leave the planner's correlated_columns_set pointing to the original non-Nullable node, and PlannerActionsVisitor::visitColumn (which uses type-sensitive equality) would then fail to identify the projected column as correlated and skip the PLACEHOLDER step that the decorrelation pass replaces.

The SELECT * REPLACE / APPLY binding issue in WHERE / HAVING / ORDER BY under group_by_use_nulls (projection matchers are resolved after the other clauses) is not part of this PR: it exists on master independently and is fixed by #118476. This PR only works on resolved query tree nodes.

Related: #118476

Closes #91119.
Closes #106377.
Closes #108931
Closes #109509

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 Bad cast exception in correlated subqueries that reference an outer column promoted to Nullable by group_by_use_nulls = 1 with GROUP BY WITH ROLLUP/CUBE/GROUPING SETS.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/104350]

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md Phase 4 Step 9):

a) Deterministic repro? Yes. The reproducer in issue #91119 (SELECT (SELECT c0) FROM (SELECT 1::Bool) t0(c0) GROUP BY c0 WITH ROLLUP SETTINGS group_by_use_nulls = 1) deterministically aborts under debug builds.

b) Root cause explained? Yes. The analyzer's nullable_group_by_keys walk in QueryAnalyzer::resolveExpressionNode stops at the first enclosing QUERY scope, so the outer scope's GROUP BY-key set is never consulted for column references inside a correlated subquery. The inner column reference keeps its non-Nullable type, the planner builds CAST wrappers and aggregate functions for that signature, and the decorrelation pass replaces PLACEHOLDER nodes with INPUT nodes whose actual types are Nullable (because the outer GROUP BY made the keys Nullable post-rollup). The precomputed wrappers then raise Bad cast from type ColumnNullable to ColumnVector<...> during header inference.

c) Fix matches root cause? Yes — the fix is in the analyzer, not the planner. PR #100365 attempted a planner-side reconciliation (reconcileInputTypesAfterDecorrelation rebuilding function_base after types change) and was rejected by @alexey-milovidov as a band-aid ("we should fix the root cause, why the types were incorrect in the first place"). The fix here lifts the analyzer walk so it consults outer scopes for correlated column references and converts them in place.

d) Test intent preserved? / New tests added? Both. The new test 04210_91119_correlated_subquery_group_by_use_nulls.sql covers WITH ROLLUP/CUBE/GROUPING SETS, Bool (the original CAST wrapper case), numeric types, complex correlated expressions (c0 + 1, c0 % 2), aggregate function over correlated outer column (anyLastOrDefault), correlated HAVING, correlated WHERE, Nullable source, and a sanity check that a non-correlated subquery is NOT affected. I also re-ran 22 existing group_by_use_nulls and correlated-subquery tests against this change — all pass. The existing aggregate-function exclusion (max(c0) inside the same query keeps c0 non-Nullable) is preserved by evaluating it per-scope rather than upfront.

e) Demonstrated in both directions? Yes. Without the fix the server crashes with Logical error: 'Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>'. With the fix the original reproducer returns true \N and the broader test set (12 query shapes) passes.

f) Fix is general, not a narrow patch? Yes. The fix is in resolveExpressionNode, which is recursively called for every expression node, so the type propagation handles columns wrapped in functions, aggregates over correlated columns, lambda-wrapped expressions, and HAVING/WHERE filter contexts uniformly. Symmetric callers (resolveFunction, resolveExpressionNodeList, etc.) all dispatch through this entry point. The match is gated on the column's source table expression so unrelated identically-named columns in non-correlated subqueries are not affected.

Session: cron:clickhouse-ci-task-worker:20260508-074500

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai — could you review this? It fixes #91119 by extending the analyzer's nullable_group_by_keys walk so that correlated columns referenced from inside a subquery pick up the Nullable type promotion from the outer scope's GROUP BY ROLLUP/CUBE/GROUPING SETS, which was previously silently lost and caused Bad cast ColumnNullable -> ColumnVector exceptions during planner header inference.

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim — invited me here. The reproducer from #91119 (and related cases — CUBE, GROUPING SETS, aggregate function over correlated outer column, HAVING/WHERE with correlated subqueries, Nullable source) all return correct results with this fix. Also non-regressed against the existing 02343_group_by_use_nulls / 02535_analyzer_group_by_use_nulls / 03014_analyzer_group_by_use_nulls / 03315_analyzer_correlated_subqueries and the four 03408/03411 correlated subquery test suites.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20dfe0b]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, parallel) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
04210_91119_correlated_subquery_group_by_use_nulls FAIL cidb
Too many test failures FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL

AI Review

Summary

The PR extends group_by_use_nulls handling across correlated scopes, preserves correlated-column identity during deduplication, and fixes direct APPLY calls to grouping. The previous scalar-function return-type defect is addressed, but the new long regression test fails and callable expansion still bypasses the grouping exclusion. Changes are requested.

Findings

⚠️ Majors

  • Regression test:343: The new 04210 test stops with AMBIGUOUS_COLUMN_NAME because isNull(__table3.a) has both UInt8 and Nullable(UInt8) types. Earlier expected results are also stale: correlated tuple subtotals produce (1,NULL) instead of \N, and the 109509 function-argument subtotal produces 2 instead of \N. Both the PR binary and exact base reproduce these behaviors. Make the whole fixture pass without losing the intended coverage; fix or explicitly track the existing planner exception.
  • QueryAnalyzer.cpp:3077: The unresolved-name scan misses grouping behind named lambdas and SQL UDFs. WITH x -> grouping(x) AS g SELECT * APPLY x -> g(x) FROM numbers(1) GROUP BY number WITH ROLLUP ORDER BY 1 SETTINGS group_by_use_nulls = 1 throws BAD_ARGUMENTS; the direct call and the named-lambda query with group_by_use_nulls = 0 return 0, 1. Preserve key types through callable expansion and cover this path, or link an issue tracking the remaining existing limitation.
Tests
  • ⚠️ 04326 matches its reference. 04210 fails with the PR's CI Fast test binary in both local and server execution; the exact base binary confirms that the reported exception and stale outputs are pre-existing. A successful complete 04210 run and focused named-lambda/SQL-UDF coverage are still needed.
Final Verdict

Status: ⚠️ Request changes. Make 04210 pass on the current head and fix or explicitly track the remaining callable-expansion gap.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 8, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI Status — covered SHA 30c60275

Master-merge commit 30c60275 brings the analyzer correlated-rollup fix up to current trunk. CI fully finished. Sole "code" failure is a chronic Fast-test infra hang signature, not PR-caused.

Check Test Disposition
Fast test Server died Chronic Fast-test infra flake. The Fast-test runner reports WARNING: Timeout exceeded [300], sending SIGTERM followed by Hung check failed: server is not responding. CIDB 30d shows Server died is endemic across 100+ PRs (top: PR #104754=33, PR #100185=83) and master (20 hits). Last-test-before-hang on this run was 01548_uncomparable_columns_in_keys at 06:13:31, then a 42-second silence before the timeout — clearly not produced by the analyzer changes in this PR (analyzer/group-by-use-nulls).
Mergeable Check / PR / CH Inc sync n/a Aggregator/infra rollup of the above.

Code change unchanged since 2026-05-08. The 22 related existing tests still pass; the comprehensive new test 04210_91119_correlated_subquery_group_by_use_nulls.sql (12 query shapes) verifies the analyzer-level fix. Awaiting @novikd / @KochetovNicolai re-review.

— cron:our-pr-ci-monitor:20260604-073000

@groeneai groeneai mentioned this pull request Jun 8, 2026
1 task done
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 8, 2026
The previous commit replaced the OR-accumulated aggregate-function check in
`resolveExpressionNode` with a per-scope check, intending to allow the walk to
continue past the enclosing `QUERY` scope for correlated subqueries. That
broke `* APPLY x -> agg(x, key)` queries under `group_by_use_nulls = 1`:

  * The LAMBDA scope sees the aggregate on its `expressions_in_resolve_process_stack`
    but its own `nullable_group_by_keys` is empty, so the per-scope check skips
    that scope's lookup.
  * The outer `QUERY` scope holds the keys but its own stack does not see the
    aggregate (the aggregate lives inside the lambda body), so the per-scope
    check finds the key and wraps the inner reference as `Nullable`.
  * The aggregate's `addBatchSinglePlace` then runs on a `ColumnNullable` where
    its signature expects `ColumnVector<UInt64>` (or `ColumnString` for the
    `min` family), and the `assert_cast` faults inside `SingleValueDataFixed::set`.

Fast test on PR ClickHouse#104350 SHA `30c602753b` reproduced this on
`04067_group_by_use_nulls_apply_aggregate.sql` (server died, signal 11 in
`AggregateFunctionNullVariadic::addBatchSinglePlace`). The exact same shape
appears in the AST-fuzzer findings tracked under STID `0250-30be`,
`1499-22cb`, `3336-34e8`, and `3336-2f87`.

Restore the OR-accumulated `in_aggregate_function_scope` flag for scopes
within the same query nesting level, and reset it when crossing into an
outer `QUERY` scope. The reset preserves the new correlated-subquery
behaviour: an outer scope's GROUP BY keys are evaluated relative to the
outer scope's own resolution context, so an aggregate in an inner subquery
must not shield against the outer scope's `nullable_group_by_keys`.

Adds a regression test
`04326_91119_apply_lambda_aggregate_rollup.sql` covering nine variants of
`* APPLY <lambda>` plus an aggregate plus `ROLLUP` / `CUBE` / `GROUPING SETS`
under `group_by_use_nulls = 1`, including the regex-filtered APPLY shape from
issue ClickHouse#98190 (STID `1499-22cb`). The existing
`04067_group_by_use_nulls_apply_aggregate` continues to pass.

Local verification: master HEAD passes; PR HEAD without this fix aborts on
`04067` query 1; PR HEAD with this fix passes `04067`, `04210` (PR's own
test), and `04326` (new regression test).

Related: ClickHouse#91119
Related: ClickHouse#98190

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. build/programs/clickhouse local -q "SET group_by_use_nulls = 1; SELECT * APPLY x -> argMax(x, number) FROM numbers(1) GROUP BY GROUPING SETS ((materialize(65537)), (*));" aborts with SIGABRT on PR HEAD 30c602753be (without the new commit), passes on master HEAD 7a725b4ef59, and passes on PR HEAD + the new commit. Single command, every run.
b Root cause explained? Yes. The previous commit replaced the OR-accumulated in_aggregate_function_scope check in QueryAnalyzer::resolveExpressionNode with a per-scope check, intending to allow the walk to continue past the enclosing QUERY scope for correlated subqueries. For * APPLY x -> agg(x, key) queries the LAMBDA scope sees the aggregate on its expressions_in_resolve_process_stack but its own nullable_group_by_keys is empty (per-scope check skips); the outer QUERY scope holds the keys but its own stack does not see the aggregate (per-scope check finds the key and wraps the inner reference as Nullable). The aggregate's addBatchSinglePlace then runs on a ColumnNullable where the function signature expects ColumnVector<UInt64> (or ColumnString for the min family), and the assert_cast inside SingleValueDataFixed::set faults. The Fast test crash on 04067_group_by_use_nulls_apply_aggregate (signal 11 in AggregateFunctionNullVariadic::addBatchSinglePlace) and the AST-fuzzer findings under STID 0250-30be, 1499-22cb, 3336-34e8, 3336-2f87 are all the same shape.
c Fix matches root cause? Yes. Restore the OR-accumulated in_aggregate_function_scope flag for scopes within the same query nesting level, and reset it when crossing into an outer QUERY scope. The OR within a query reproduces the original (pre-correlated) suppression that the aggregate "consumes" the GROUP BY nullability boundary regardless of which scope recorded it; the reset across QUERY boundaries preserves the new correlated-subquery behaviour: an aggregate in an inner subquery must not shield against an outer scope's nullable_group_by_keys. The fix targets the analyzer-level scope walk, not the cast site.
d Test intent preserved / new tests added? Yes. Existing test 04067_group_by_use_nulls_apply_aggregate (the one Fast test failed on) continues to pass without modification. PR's own new test 04210_91119_correlated_subquery_group_by_use_nulls continues to pass without modification. New regression test 04326_91119_apply_lambda_aggregate_rollup.sql added, covering nine variants of * APPLY <lambda> plus an aggregate plus ROLLUP / CUBE / GROUPING SETS under group_by_use_nulls = 1, including the regex-filtered APPLY shape from issue #98190 (STID 1499-22cb), nested aggregate inside a function, function-form APPLY, and a non-aggregate APPLY sanity row that confirms the suppression is genuinely scoped to the aggregate-argument path and not a blanket disable.
e Both directions demonstrated? Yes. Built two binaries from the same PR HEAD on the same machine. Without the new commit: 04067 query 1 aborts with SIGABRT (core dumped); 04326 aborts on its first query. With the new commit: 04067, 04210, and 04326 all run to completion and produce output matching their .reference files.
f Fix is general, not a narrow patch? Yes. The fix is at the analyzer-level scope walk (QueryAnalyzer::resolveExpressionNode), not at any cast site. All paths that resolve column references under group_by_use_nulls = 1 benefit. The new test exercises 9 distinct shapes (regular ROLLUP/CUBE/GROUPING SETS, multiple aggregate functions including argMax, sum, min-via-function-form-APPLY, regex-filtered APPLY, nested aggregate-inside-toString, deeply-nested aggregate, and a non-aggregate APPLY sanity row). The fix traces the bad value to its origin (the analyzer setting up a wrong scope walk) instead of guarding against the symptom downstream.

Session id: cron:clickhouse-ci-task-worker:20260608-134700

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger - covered SHA: 6f52db2

Workflow PR finished 2026-06-08T18:52:53Z. Triage of the four reds:

Check Failure Classification Disposition
BuzzHouse (amd_debug) Logical error: Mutation of \Memory` table produced incomplete output (STID: 2380-2e8c)` chronic trunk bug Tracked. Active fix PR #106615. 30-day cross-PR: 14 master hits, 30+ unrelated PRs. PR diff is src/Analyzer/Resolve/QueryAnalyzer.cpp + a stateless test only - completely unrelated to Memory table mutation pipeline.
BuzzHouse (amd_tsan) Same STID family (2380-3043) chronic trunk bug Same as above.
Mergeable Check aggregator reflects the two BuzzHouse fails clears when STID 2380 family clears.
PR aggregator reflects above same.

The Fast-test failure on 04067_group_by_use_nulls_apply_aggregate from the prior HEAD has been fixed by this commit (analyzer per-scope check now restores OR-accumulated in_aggregate_function_scope for scopes within the same query nesting level, matching the original semantic). All other 143 checks pass.

Session: cron:our-pr-ci-monitor:20260608-193000

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master (branch was ~1547 commits / ~7 days behind and red) — clean merge, no conflicts.

Addressed both review threads in 62084af:

  • Correctness (QueryAnalyzer.cpp:3440): an outer scope's nullable_group_by_keys is now applied to a correlated column only when that scope actually owns the column's source table expression (registered_table_expression_nodes.contains(column_source)), mirroring the ownership test already used at the QUERY-boundary break. This prevents an intermediate query with a same-named, same-typed GROUP BY key from matching a correlated outer column (ColumnNode::isEqualImpl compares only name + type, not source). The deeper multi-level scenario is currently NOT_IMPLEMENTED in the planner, so this is a defensive guard; single-level correlated cases are unaffected (existing tests pass).
  • Stale comment (QueryAnalyzer.cpp:3406): rewritten to describe the actual OR-accumulate-within-query / reset-at-QUERY-boundary rule.

Verified locally: the #91119 reproducer now returns Nullable values instead of the Bad cast exception, and both 04210/04326 tests pass against the rebuilt binary.

Remaining CI reds are all the BuzzHouse Logical error: Mutation of Memory table produced incomplete output finding (STID 2380) in StorageMemory::mutate on ALTER ... APPLY PATCHES/MODIFY TTL — unrelated to this analyzer change.

@groeneai

groeneai commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: 62084af978d84d75e9f27292fa61bbcd70c1cb42

Workflow PR finished 2026-06-09T13:10:28Z (success); Finish Workflow and Mergeable Check pass; gate satisfied (≥20 min CIDB ingestion buffer met, no jobs queued/in-progress). CIDB reports zero FAIL/ERROR rows on this HEAD across all 162 completed jobs — every Stateless / Integration / AST fuzzer / BuzzHouse / Stress / Unit / Performance / SQLLogic / Compatibility / Install variant is green.

The previous ledger covered 6f52db2ce0c (analyzer OR-accumulated in_aggregate_function_scope restore). HEAD advanced to 62084af978d after @ alexey-milovidov pushed the master merge plus the correctness guard at QueryAnalyzer.cpp:3440 and the comment rewrite at :3406 to address his own earlier review threads — both are resolution commits, not new directives. Local verification (issue #91119 reproducer, 04067_group_by_use_nulls_apply_aggregate, the new 04326_91119_apply_lambda_aggregate_rollup regression test) confirmed the fix held.

No outstanding CI items. Awaiting human review on the analyzer change.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed be05b67e0cc reworking the group_by_use_nulls correlated-wrapping logic along the lines discussed in the C1/C3 threads. Extracted it into applyGroupByUseNullsToExpression and made it driven by whether the resolved expression is correlated, using the existing CorrelatedColumnsCollector instead of node->as<ColumnNode>()->getColumnSourceOrNull().

What changed per comment:

  • C1 / C2 (compound key c % 2): correlation is now a property of the expression's columns, not its top-level node type. CorrelatedColumnsCollector collects correlated columns from the whole subtree, so c % 2 is recognised and wrapped in place. EXPLAIN QUERY TREE for SELECT (SELECT c0 % 2) FROM (SELECT toInt32(3)) t0(c0) GROUP BY c0 % 2 WITH ROLLUP now shows modulo(c0, 2) Nullable(Int16) instead of Int16.
  • C3 (if (!column_source) break;): replaced with if (!is_correlated() || ownsCorrelatedSource(...)) break;. The walk continues past a QUERY boundary only for a genuinely correlated expression and only until the scope that owns the correlated source, so an intermediate query with a same-named key cannot match.
  • C4 (in_aggregate_function_scope = false;): the reset now happens only on the deliberate continuation into an outer query for a not-yet-resolved correlated expression (see the thread reply).

One honesty note on scope: the compound-key correlated shapes (C1/C2) are currently rejected by the planner before execution, on both master and this branch:

SELECT (SELECT c0 % 2) FROM (SELECT toInt32(3)) t0(c0) GROUP BY c0 % 2 WITH ROLLUP
-> NOT_IMPLEMENTED: can't find correlated column '__table3.c0' in current header: __grouping_set, modulo(__table3.c0, 2_UInt8)

So this part of the change fixes the analyzer's type, which is the correctness issue you flagged, but there is no runnable query that demonstrates a row-level difference for it yet. The reachable shapes (bare GROUP BY key, with bare or compound correlated references, plus the original * APPLY ... argMax cases) are covered by the runtime regression tests 04210 and 04326, which still pass, and I confirmed no regressions across the *group_by_use_nulls* and *correlated* stateless suites. Happy to add an EXPLAIN QUERY TREE test that locks in the c % 2 Nullable type if you want one, or to hold it until the planner supports the shape.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. The original crash family (* APPLY x -> argMax(x, key) + ROLLUP under group_by_use_nulls) is covered by 04326; the reviewed type bug is EXPLAIN QUERY TREE SELECT (SELECT c0 % 2) FROM (SELECT toInt32(3)) t0(c0) GROUP BY c0 % 2 WITH ROLLUP showing Int16 before / Nullable(Int16) after.
b Root cause explained? The walk decided "is this correlated, keep walking outward" from node->as<ColumnNode>(), so a compound expression (no top-level column source) stopped at the inner QUERY boundary and never consulted the owning outer scope's nullable_group_by_keys. Correlation is a property of the subtree's columns, not the top-level node.
c Fix matches root cause? Yes. The walk is now driven by CorrelatedColumnsCollector (subtree correlation) and source ownership, so it handles bare columns and compound expressions uniformly and stops at the owning scope.
d Test intent preserved / new tests added? 04210 and 04326 unchanged and still pass. No test weakened. The fix is a refactor of the same wrapping logic with broader correctness; the compound-key case has no runnable test (planner NOT_IMPLEMENTED, see above).
e Both directions demonstrated? Yes. 04326 aborts on the no-fix branch and passes with the fix; the c % 2 type is Int16 without the rework and Nullable(Int16) with it.
f Fix is general, not a narrow patch? Yes. Drives off the canonical correlation mechanism rather than a special-case top-level-column check, covering all expression shapes, and adds a fast path so non-group_by_use_nulls queries pay only a cheap scope-chain check.

Session id: cron:clickhouse-worker-slot-5:20260610-090200

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed e8d62a69667 to fix two Fast test regressions that the previous commit (be05b67e0cc) introduced. The previous commit drove the wrapping by expression correlation (addressing the c % 2 / source-ownership review feedback) but regressed non-correlated GROUP BY keys referenced inside lambda bodies.

What broke and why: applyGroupByUseNullsToExpression used scope_ptr == &scope as the discriminator for the non-correlated clone-and-wrap branch. A GROUP BY key referenced inside a lambda body, e.g. arrayMap(x -> intDiv(x, key), ...) where key is a GROUP BY key of the surrounding query, is resolved with &scope pointing at the LAMBDA scope while the key lives in the enclosing QUERY scope. That reference is not correlated, so it matched neither the scope_ptr == &scope clone branch nor the correlated ownsCorrelatedSource branch and was left non-Nullable. Result: 04001_logical_error_with_cube emitted an extra row (arrayMap returned Array(UInt8) instead of Array(Nullable(UInt8)), changing DISTINCT semantics) and 03023_group_by_use_nulls_analyzer_crashes hit Cannot capture column N ... got Nullable(UInt8), but UInt8 is expected (LOGICAL_ERROR).

Fix: take the clone-and-wrap branch for any non-correlated match (scope_ptr == &scope || !is_correlated()), not just the scope_ptr == &scope case. The scope_ptr == &scope check is kept as a fast path so the common direct-projection match skips the correlated-columns analysis. The correlated in-place wrap (gated by ownsCorrelatedSource) and the compound-key correlated case are unchanged.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. 04001 reproduces via clickhouse-local (extra 1 [] row). 03023 reproduces via the test runner against a server built from be05b67e0cc: deterministic LOGICAL_ERROR Cannot capture column 2 ... got Nullable(UInt8), but UInt8 is expected, server SIGABRT (exit 134).
b Root cause explained? Yes. The previous commit used scope_ptr == &scope to decide the non-correlated clone branch. A non-correlated key referenced inside a lambda body has &scope = LAMBDA scope and the key in the enclosing QUERY scope (scope_ptr != &scope), and CorrelatedColumnsCollector returns empty for it, so it fell through both branches and stayed non-Nullable. The resulting type mismatch (wrapped projection vs unwrapped lambda capture) causes the extra DISTINCT row (04001) and the capture LOGICAL_ERROR (03023).
c Fix matches root cause? Yes. The discriminator becomes "is this reference correlated?": scope_ptr == &scope || !is_correlated() takes the clone-and-wrap branch for any non-correlated match (direct or lambda-nested), exactly the case the previous commit dropped. Not a band-aid: the EXPLAIN QUERY TREE for 04001 is now byte-identical to the green parent 62084af978d.
d Test intent preserved / new tests added? Preserved. No tests modified. 03023 and 04001 are the existing regression tests that now pass; 04210 and 04326 (this PR's own tests) continue to pass; 04067_group_by_use_nulls_apply_aggregate (the earlier Fast test crash) passes. novikd's c % 2 compound-key correlated case still wraps to Nullable.
e Both directions demonstrated? Yes. be05b67e0cc: 04001 emits extra row, 03023 LOGICAL_ERROR + SIGABRT. e8d62a69667: both pass via the test runner; 04001 tree identical to green parent.
f Fix is general, not a narrow patch? Yes. The fix corrects the wrapping decision at its source (the scope-walk discriminator), covering direct-projection, lambda-body, CUBE/ROLLUP/GROUPING SETS, and correlated shapes alike. Verified against the full group_by_use_nulls suite (16/16 non-stateful pass) and 75 correlated/cube/rollup/grouping_sets tests (0 unrelated failures; the only two skips were a stateful test needing test.hits and a test hardcoding HTTP port 8123, both passing once the local env matches CI).

Session id: cron:clickhouse-worker-slot-7:20260610-104500

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: e8d62a696678d0d70504e09e17a60b1ac636ea21

CI fully finished on this HEAD (Finish Workflow = success; no checks queued/in-progress). Triaging the two remaining red checks; neither is caused by this PR.

Check Failure Classification Disposition
Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) test_refreshable_mat_view_replicated/test.py::test_circular_dependencies_survive_restart chronic flaky (NOT PR-caused) 30-day cross-PR: 14+ distinct unrelated PRs + master. Tracked under issue #106651. This PR only touches QueryAnalyzer.cpp + group_by_use_nulls tests, nothing in refreshable-mat-view / ReplicatedMergeTree.
Stateless tests (arm_asan_ubsan, azure, parallel) Server died / OOM in dmesg / Logical error: Expected 3 to 10 arguments in table function azureBlobStorage, got 1 infra outage (NOT PR-caused) The arm_asan_ubsan, azure, parallel runner is in a broad failure window: 272 distinct tests across 41 unrelated PRs failed on this exact check in the last 12h (OOM / Server died). Independent of this PR's diff.
Mergeable Check / PR / CH Inc sync aggregators downstream Reflect the two above; no independent signal.

The two Fast test failures from the prior commit (be05b67e0cc: 03023_group_by_use_nulls_analyzer_crashes, 04001_logical_error_with_cube) were PR-caused regressions from the rework and are fixed in e8d62a69667 (both verified passing locally in both directions). No PR-caused failures remain on the current HEAD.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed fd5dfbf70a1 adding two String-aggregate cases to 04210 ((SELECT min(c0)) over a String GROUP BY key with WITH ROLLUP, and minOrDefault with GROUPING SETS). These exercise the ColumnNullable -> ColumnString wrapper, distinct from the numeric ColumnVector path the other cases cover. Both crashed with Bad cast from ColumnNullable to ColumnString on master and now return the post-rollup Nullable value.

While reviewing the rework I rebuilt the PR on current master (which now contains the multistage_distributed_queries rewrite #106020, merged after this branch's last rebase) to confirm the analyzer-level fix still applies after the planner changes. Built from a fresh checkout rooted at the worktree sources (not a single-TU relink), the four headline shapes behave as expected:

case master this PR on master
(SELECT c0) Bool (#91119 headline) crash true, \N
(SELECT c0) numeric ok ok
(SELECT sum(number)) over correlated key crash ok
(SELECT min(c0)) String crash a, \N

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. clickhouse-local --enable_analyzer=1 --allow_experimental_correlated_subqueries=1 --group_by_use_nulls=1 -q "SELECT (SELECT min(c0)) FROM (SELECT 'a'::String) t0(c0) GROUP BY c0 WITH ROLLUP ORDER BY c0 NULLS LAST" aborts (exit 134, Bad cast from ColumnNullable to ColumnString) on master; same for the GROUPING SETS variant.
b Root cause explained? Same root cause as the rest of the PR: the correlated String key kept its non-Nullable type, so the planner built aggregate/CAST wrappers for ColumnString while decorrelation fed in the post-rollup Nullable(String). The fix wraps the correlated reference to Nullable in the analyzer, so the wrapper signatures match.
c Fix matches root cause? Yes. No code change in this commit; it adds coverage for the SingleValueDataString aggregate branch the existing cases did not reach.
d Test intent preserved / new tests added? New cases only; no existing assertion changed.
e Both directions demonstrated? Yes. Both queries crash on master and pass on this branch; the full 04210 reference matches.
f Fix is general, not a narrow patch? The underlying fix is type-agnostic (convertToNullable); these cases verify the String manifestation alongside the numeric and Bool ones. Regression set re-run green: 03023, 04001, 02343(+distributed), 02535, 04210, 04326 all pass.

Session id: cron:clickhouse-worker-slot-9:20260610-190100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD fd5dfbf (Finish Workflow passed). The new commit on this HEAD is test-only (2 String-aggregate cases added to 04210); the prior SHA e8d62a6 was CI-clean. Two failures, both pre-existing server crashes in subsystems disjoint from this PR's analyzer-only diff (QueryAnalyzer.cpp):

A test-only commit cannot introduce a String-serialization or disk-metadata crash; the immediately-prior build (same code, minus 2 test lines) finished CI clean. Not PR-caused. The fix (#91119 correlated ROLLUP cast) is verified in both directions; awaiting @novikd re-review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD fd5dfbf70a12. All failures are known infrastructure noise, none PR-caused. Moving to review.

Check Failure Disposition
Stateless (amd_asan_ubsan, db disk, distributed plan, sequential) Segfault STID 1288-3bd5 + Server died Infra — the 2026-06-10/11 ASan secondary-allocator OOM (CHECK failed: sanitizer_allocator_secondary.h:200), seen across many unrelated PRs in the same window. Not this PR.
Stateless (arm_asan_ubsan, azure, sequential) Segfault STID 1185-04a1 + Server died Same ASan-allocator OOM outage (azure sequential variant). Not this PR.

Fast test, Style check, and Bugfix validation are all green on this HEAD. The two stateless failures share the sanitizer_allocator_secondary.h ASan internal-allocator OOM signature that hit dozens of PRs and master between 2026-06-10 21:00 and 2026-06-11 00:30 UTC, so they are unrelated to this change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Resolved the merge conflict with master (branch was behind by ~978 commits).

The only conflict was in src/Analyzer/Resolve/QueryAnalyzer.cpp. Master commit 4f7d1c43 ("Avoid hash calculation for ColumnNode") added !nullable_group_by_keys.empty() guards to the same inline group_by_use_nulls walk that this PR had refactored into the applyGroupByUseNullsToExpression helper. Resolution: kept the helper and folded that per-scope .empty() guard into its walk, so the optimization is preserved. resolveMatcher's guard from the same master commit auto-merged cleanly (this PR never touched that function). The merged tree differs from master by exactly the six PR files; QueryAnalyzer.cpp compiles clean. CI re-running on the new HEAD.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI Ledger covered SHA: c49cfa25c244f818395343735bd1afee1afdad77

CI fully finished on the rebased HEAD (Finish Workflow + Mergeable Check both pass). One red check, NOT PR-caused:

The remaining CH Inc sync "pending" is the fork mirror sync that never completes for fork PRs (not a test).

No PR-caused failures. The conflict-resolution merge changed only the QueryAnalyzer.cpp conflict resolution (folded master's !empty() perf guard into the helper); the fix logic and the both-directions verification (Bool/sum/min-String all crash on master, pass with the fix) are unchanged.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…d-rollup-cast-wrapper

Conflicts in `src/Analyzer/Resolve/QueryAnalyzer.cpp`:
- anonymous namespace: kept both the PR's `ownsCorrelatedSource` and master's new helpers.
- `resolveMatcher`: kept the PR's `applyGroupByUseNullsToExpression` call for `APPLY` results
  before master's new projection-naming logic.
- `resolveQuery`: master added a `GROUP BY ALL` branch under `group_by_use_nulls`. Its throwaway
  projection resolution already applies `REPLACE` mappings to the unresolved clauses, so
  `applyReplaceTransformersToUnresolvedClauses` now runs only in the non-`GROUP BY ALL` branch.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch to clear the conflict (merge commit d9c6cd9). No behaviour changes beyond the merge.

src/Analyzer/Resolve/QueryAnalyzer.cpp had three conflicts:

  • Helpers in the anonymous namespace: kept both sides.
  • resolveMatcher: kept this PR's applyGroupByUseNullsToExpression call for APPLY results. It now runs before master's new APPLY (…, 'prefix') projection-naming block.
  • resolveQuery: master added a GROUP BY ALL branch under group_by_use_nulls. That branch does a throwaway projection resolution while the other clauses are still unresolved, so resolveMatcher already applies the REPLACE mappings there. applyReplaceTransformersToUnresolvedClauses therefore runs only in the non-GROUP BY ALL branch, so identifiers inside a substituted expression are not rewritten a second time. I checked SELECT * REPLACE (a + 1 AS a) … GROUP BY ALL WITH ROLLUP HAVING a = 2: group_by_use_nulls = 0 and = 1 return the same rows.

Local checks:

  • ninja clickhouse builds clean.
  • All five 91119 tests match their .reference byte for byte.
  • I ran 102 stateless tests that match group_by_use_nulls, GROUP BY ALL or the APPLY prefix. 85 pass. The other 17 need a cluster, ZooKeeper or the test database, which the local setup doesn't have.

The previous head's reds (Bugfix validation harness abort, and new_tests_check.py failing as a result) came from the S3 lookup fixed by #117580. This merge brings that fix in.

As agreed above, we're still waiting for #118476 to land. It is open as of 2026-09-23. Once it lands, this branch will be cut down to the correlated-subquery subset, which drops the IdentifierNode pre-pass that @novikd objected to.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits October 2, 2026 09:46
…TIL` under `group_by_use_nulls`

The deferred pre-pass `applyReplaceTransformersToUnresolvedClauses` replayed the
`SELECT * REPLACE` mappings into seven clauses but not into the `LIMIT AFTER` /
`LIMIT UNTIL` boundaries, which the eager `resolveMatcher` path rewrites. With
`group_by_use_nulls = 1`, `SELECT * REPLACE(a * 10 AS a) ... GROUP BY a WITH ROLLUP
ORDER BY a LIMIT UNTIL a >= 30` raised `NOT_AN_AGGREGATE` instead of returning
`0, 10, 20`. Rewrite both boundaries too and add the rollup/cube variant as a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

Remove `applyReplaceTransformersToUnresolvedClauses` and its helper
`collectMatcherProducedColumnNames`. They rewrote `IdentifierNode`s in the
unresolved query tree, which the reviewer pointed out is incorrect, and the
approximation of the matcher resolution kept diverging from
`resolveQualifiedMatcher` / `resolveUnqualifiedMatcher` (qualified matchers,
`ARRAY JOIN` aliases).

The `SELECT * REPLACE` / `APPLY` ordering problem under `group_by_use_nulls`
exists on `master` independently of the correlated subquery fix and is
handled properly by ClickHouse#118476,
which expands projection matchers before the other clauses. This PR is now
cut down to the correlated subquery part: `applyGroupByUseNullsToExpression`
and the `addCorrelatedColumn` deduplication, both working on resolved nodes
only.

The tests that covered only the `REPLACE` rewrite (04696, 05037, 05055,
05317 and the `REPLACE` sections of 04326) are removed together with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 17, 2026 18:00
# Conflicts:
#	src/Analyzer/Resolve/QueryAnalyzer.cpp
`GROUPING SETS (..., ())` without aggregate functions now emits the row of
the empty grouping set (ClickHouse@1d48d4bf5f0),
so the `GROUPING SETS` cases of these tests return one more row. Also sort the
`max(if(1, 2, a.k))` case so its mixed `NULL`/non-`NULL` rows are deterministic.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104350&sha=eb39e6c568d7cfcae17752cabbdaf7b7729bf2af&name_0=PR&name_1=Fast%20test
PR: ClickHouse#104350

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

alexey-milovidov commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflict in QueryAnalyzer.cpp:

  • The matcher path uses master's findNearestScopeWithNonEmpty / isInAggregateOrGroupingFunctionScope and keeps this PR's grouping-aware APPLY exclusion.
  • resolveExpressionNode keeps the call to applyGroupByUseNullsToExpression.
  • Master's new nullable_collapsed_group_by_key_columns handling (correlated columns that IfConstantConditionPass collapses an outer if key to) is moved into applyGroupByUseNullsToExpression. It applies only at the scope that owns the correlated source, as before.

The Fast test failure in 04326 (and the same pattern in 04210) came from 1d48d4bf5f0. That commit makes GROUPING SETS (..., ()) without aggregate functions emit the empty-set row. I updated both references and sorted the one affected query that had no ORDER BY. Locally, 161 of 174 related tests (group_by_use_nulls, rollup, grouping sets, correlated, matcher) pass, including 04210 and 04326 after the update. The other 13 fail only because of the environment (no remote replicas on 127.0.0.2, no test.hits dataset, no MinIO, no stateless worker cluster).

@novikd: as of eb39e6c568d this PR no longer touches IdentifierNodes or the unresolved tree. Could you take another look?

…lated references

`applyGroupByUseNullsToExpression` reset `is_aggregate_or_grouping_argument` when the
walk crossed into an outer query for a correlated expression, but then OR-ed the outer
query's expression stack into it again. When the correlated subquery is reached through
an alias first resolved inside an aggregate (e.g. `covarSamp(x, y)` in a GROUP BY key
branch that `if` with a constant condition drops), the correlated column stayed
non-Nullable while decorrelation feeds it the outer post-aggregation Nullable column,
causing the `Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>`
exception. On `master` the aggregate guard was bypassed for correlated columns; restore
that by not accumulating the flag after crossing into an outer query.

Found by the stress test (amd_msan):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104350&sha=f82eb9ed827f7642fb775c668fce124fe12f0878&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
PR: ClickHouse#104350

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status as of 2026-10-20:

  • The Stress test (amd_msan) failure (Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>, report) was caused by this PR: it reproduces on the PR build and not on master. When the walk in applyGroupByUseNullsToExpression crossed into the outer query for a correlated reference, it reset the aggregate flag but then picked up the outer query's expression stack again. A correlated subquery reached through an alias first resolved inside an aggregate (here covarSamp(x, y) in a GROUP BY branch that if(82, ...) drops) therefore stayed non-Nullable. f0af6f0 stops accumulating the flag after the boundary, as master did for correlated columns, and adds the reduced query to 04210. 04210, 04326 and 05385 pass locally.
  • @novikd, your remaining thread is addressed: since eb39e6c the PR no longer touches IdentifierNodes or the unresolved query tree. Only applyGroupByUseNullsToExpression and the addCorrelatedColumn deduplication remain, and both work on resolved nodes. Could you take another look?

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits November 2, 2026 22:19
…group_by_use_nulls`

`applyGroupByUseNullsToExpression` called `convertToNullable` on a correlated
`FunctionNode` that matched an outer `GROUP BY` key. Such a function is recomputed
inside the subquery from its (already wrapped) arguments, and
`FunctionNode::convertToNullable` only changes its declared result type, so for
`isNull`, `ifNull`, `assumeNotNull` and similar the executed type did not match:
`LOGICAL_ERROR: Unexpected return type from isNull. Expected Nullable(UInt8). Got UInt8`.

Wrap only correlated columns in place, as before this PR. Replace the `EXPLAIN QUERY TREE`
pin of a Nullable correlated `modulo` (that query is not executable anyway: the planner
cannot find the correlated column `c` in the aggregated header) with execution
regressions for `isNull`, `ifNull` and `assumeNotNull`.

PR: ClickHouse#104350

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @novikd, your change request (2026-09-08: "It is incorrect to touch IdentifierNodes and modify the unresolved query tree") was addressed in eb39e6c. applyReplaceTransformersToUnresolvedClauses and collectMatcherProducedColumnNames are gone, and the SELECT * REPLACE ordering under group_by_use_nulls is left to #118476. The PR now works only on resolved nodes: applyGroupByUseNullsToExpression, which as of f52d9ba wraps only a correlated ColumnNode, plus the addCorrelatedColumn deduplication. Master was merged on 2026-11-02, CI is green, and all review threads are resolved. Could you take another look?

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

-- (Nullable) arguments, so it must keep the result type inferred by the function. Declaring it Nullable
-- raised "Unexpected return type from isNull. Expected Nullable(UInt8). Got UInt8".
SELECT '-- correlated function matching an outer key keeps its own result type ---';
SELECT a, (SELECT isNull(a))

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.

[Major] The new 04210 regression does not pass on the current head. Running the complete file with this PR's Fast test binary, both via clickhouse local and against a server, stops at this query with AMBIGUOUS_COLUMN_NAME: isNull(__table3.a) appears as both UInt8 and Nullable(UInt8) in the same block. The earlier Unexpected return type issue is fixed, but this is a different failure later in planning.

The reference also disagrees with earlier successful queries: the correlated tuple subtotal is now (1,NULL) rather than \N, and the last row of the 109509 function-argument case is 2 rather than \N. Running against base ed426a200679a7512bad37c61b17f49876fa3f8c reproduces these same failures, so these are existing behaviors exposed by the new fixture, rather than regressions introduced by this helper.

Please make the complete new test execute and match its reference on the current head while retaining its regression coverage. Update expectations where the behavior has intentionally changed; if the remaining planner exception is deferred, link its tracking issue and retain an executable regression for the type-handling fix.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The AMBIGUOUS_COLUMN_NAME in 04210 on 20dfe0b comes from #129971, which reached this branch with the master merge: it joins the decorrelated subquery on a null-safe key, and that key's isNull(__table3.a) part takes the name of the outer GROUP BY key. Fix: #132567. The other changed values in 04210 (the subtotals for a NULL outer value) are #129971's intended semantics, so that part of the reference needs updating.

{
if (AggregateFunctionFactory::instance().isAggregateFunctionName(func->getFunctionName()))
if (AggregateFunctionFactory::instance().isAggregateFunctionName(func->getFunctionName())
|| func->getFunctionName() == "grouping")

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.

[Major] The new grouping exclusion misses named lambdas and SQL UDFs because it scans the unresolved call's surface name. For example:

WITH x -> grouping(x) AS g
SELECT * APPLY x -> g(x)
FROM numbers(1)
GROUP BY number WITH ROLLUP
ORDER BY 1
SETTINGS group_by_use_nulls = 1;

This throws BAD_ARGUMENTS with GROUPING function argument number is not in GROUP BY keys, whereas direct APPLY x -> grouping(x) and the same named-lambda query with group_by_use_nulls = 0 both return 0, 1. The scan sees only g, so the key becomes Nullable before resolveFunction expands the lambda into grouping. A registered SQL UDF wrapping grouping has the same problem. This also exists in the scalar lambda-call path on the base; the new exclusion leaves that representation of the same operation uncovered.

Please preserve the original key type through callable expansion and add a named-lambda/SQL-UDF regression, or link a tracking issue if that part of the fix is intentionally deferred.

This branch has not been deployed

No deployments
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 comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

8 participants