Repository navigation
Fix wrong result and LOGICAL_ERROR for a matcher inside a lambda with join_use_nulls / group_by_use_nulls - #111993
Conversation
…ls promotion QueryAnalyzer::resolveMatcher applied both nullability promotions by reading state off the scope it was handed: join_use_nulls iterated scope.registered_table_expression_nodes, and group_by_use_nulls looked matched columns up in scope.nullable_group_by_keys. Both containers are populated only on the query scope that owns the join tree, and IdentifierResolveScope's constructor copies neither to a child scope. A lambda body is resolved in a fresh child scope, so inside a lambda both promotion blocks were dead code and the matched columns kept their pre-promotion types. Column discovery still worked because it reaches through with scope.getNearestQueryScope(); that asymmetry was the bug. The single-identifier path promotes from the join kind and side it computed while walking the join tree, which is why b.x worked inside a lambda while b.* did not. Downstream, ActionsDAG::updateHeader binds header columns to DAG input nodes by name, so the JOIN's promoted Nullable column met the analyzer's non-Nullable input node and ColumnFunction::appendArgument's type-identity check fired. Three user-visible bugs are fixed: - join_use_nulls = 1 with a matcher in a lambda over the NULL side of a LEFT/FULL JOIN returned a value computed over defaults for unmatched rows instead of NULL, and aborted in debug and sanitizer builds. - group_by_use_nulls = 1 with a matcher in a lambda and WITH ROLLUP, WITH CUBE or GROUP BY GROUPING SETS failed with NOT_AN_AGGREGATE, because the non-promoted matcher column no longer matched the promoted GROUP BY key. - An expression containing a lambda in PREWHERE combined with a JOIN and join_use_nulls = 1 aborted, with or without a matcher. Both promotion blocks now read their state from the nearest scope that owns it, bounded at the enclosing QUERY/UNION scope so a lambda in an inner subquery cannot adopt an outer query's join tree or GROUP BY keys. The owning scope is passed to convertJoinedColumnTypeToNullIfNeeded, because it records the type change in scope.join_columns_with_changed_types and the PREWHERE rollback reads that map only from the query scope. group_by_use_nulls promotion must not apply to pre-aggregation values, and the block's aggregate guard read the immediate scope only. ExpressionsStack is per-scope, so an aggregate enclosing a lambda sits on a parent scope's stack; the guard is now the same cross-scope scan resolveExpressionNode already uses. join_use_nulls nullability is a property of the join output, so it deliberately has no such guard. PREWHERE is evaluated storage-side, before the join, so its expressions must keep pre-join types. resolveQuery enforced that by re-resolving PREWHERE and undoing promotions with ReplaceColumnsVisitor, whose needChildVisit does not descend into LAMBDA, so the rollback could not reach a lambda body. Rather than deepen the rollback, join_use_nulls is now cleared on the query scope while PREWHERE is resolved, so the promotion never happens there. This mirrors the existing USING-column alias site. A subquery nested inside PREWHERE re-reads the setting from its own context, so its own join is unaffected. Found by the AST fuzzer inside the stress test on unrelated pull requests (STID 3293-4e7f), never on master.
Section 12d covers a JOIN USING with same-typed keys, an unqualified matcher inside a lambda and join_use_nulls = 1. On the unfixed analyzer the RIGHT and FULL cases abort with "Cannot capture column 2 ... got Tuple(UInt8, Nullable(UInt64))"; nothing in the file asserted that combination, because 9b is USING without PREWHERE and 12 is PREWHERE without USING. The cases are recorded both with and without PREWHERE because PREWHERE turns out not to be the ingredient: the same queries abort without it and with WHERE substituted, while a matcher genuinely inside the PREWHERE predicate does not abort at all. Only the unqualified matcher path reproduces; the qualified form resolves through the owning scope already. Reverting the scope walk in resolveMatcher alone breaks exactly the four matcher statements while their explicit-column oracles and the join_use_nulls = 0 and LEFT JOIN controls keep passing, so these are assertions on that walk rather than on the PREWHERE promotion suppression. Co-Authored-By: Claude Fable 5 <[email protected]>
The USING branch of resolveUnqualifiedMatcher passed the scope it was handed to createProjectionForUsing. Inside a lambda that scope is a fresh child, and a child scope with a context re-reads join_use_nulls from that context, so it carries true even after the PREWHERE resolve cleared the flag on the query scope. The merged USING key was therefore promoted to Nullable inside a PREWHERE lambda while the equivalent explicit column kept its pre-join type, and the rollback could not undo it: convertJoinedColumnTypeToNullIfNeeded records the change in the scope it is given, whereas the PREWHERE rollback reads that map only from the query scope, and ReplaceColumnsVisitor cannot descend into a lambda body in any case. Pass the owning query scope instead, mirroring what the sibling promotion in resolveMatcher already does. Only FULL JOIN is affected in practice: createProjectionForUsing returns the surviving side's own argument for RIGHT and LEFT, and need_nullable never promotes that side, so only FULL keeps both arguments and can promote the merged key. Test 12e pins the type and the resulting rows against the explicit-column oracle in the same PREWHERE position, with join_use_nulls = 0, LEFT and RIGHT controls and a WHERE counterpart, since WHERE runs after the join and the promoted type is correct there. Reverting this change alone breaks exactly the two FULL JOIN type assertions and nothing else. Co-Authored-By: Claude Fable 5 <[email protected]>
The test asserts 42 toTypeName() values that only the new analyzer can produce, and the whole fix lives in src/Analyzer/Resolve/QueryAnalyzer.cpp, which is dead code when enable_analyzer = 0. Three CI jobs run with the old analyzer (tests/config/install.sh links tests/config/users.d/analyzer.xml for --analyzer, and ci/jobs/functional_tests.py maps the "old analyzer" job option to that flag). Two of them are stateless jobs in the functional_tests_jobs group, so they run on every PR. There is no .oldanalyzer.reference, so clickhouse-test compares the plain .reference against an old-analyzer server: measured on a real old-analyzer server, the test failed on the section 12d type assertions (Array(Tuple(Nullable(UInt8), ...)) instead of the pre-promotion Array(Tuple(UInt8, ...))). Pinning the setting keeps the test running and asserting on those jobs. A no-old-analyzer tag would skip it there instead and throw the coverage away. analyzer.xml declares no constraints, so a session SET overrides the profile. The reference is unchanged.
Internal second-model review (click to expand)An independent reviewer model and an automated review gate examined this change before it was
Noted, not blocking: the unguarded Session id: cron:clickhouse-review-slot-11:20260726-223253 |
Pre-PR validation gate (click to expand)
Also verified: 50/50 randomized runs of the new test pass, and a targeted sweep of 646 existing tests matching |
|
cc @vdimir @yakov-olkhovskiy — could you review this? |
|
Workflow [PR], commit [8d90a8d] Summary: ✅
AI ReviewSummaryThis PR fixes the main matcher-in-lambda regressions by making Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 83de118.
Changed lines: Changed C/C++ lines covered: 52/53 (98.11%) · Uncovered code |
resolveUnqualifiedMatcher suppresses the synthetic merged USING key when the key is absent from a table expression's own columns, which happens when analyzer_compatibility_join_using_top_level_identifier resolves the key to a SELECT projection alias. That check read table_expression_node_to_data from the scope it was handed, but the map is populated only on the scope owning the join tree: a lambda body resolves in a fresh child scope where it is empty, so the lookup missed, the suppression never fired, and a matcher inside the lambda matched the merged key while the same matcher at the top level did not. Read the map from nearest_query_scope, matching the two promotion sites in the same block. Unlike the other fixes in this pull request this one is independent of Nullable promotion: it reproduces with join_use_nulls = 0 as well. Reported by the automated reviewer on ClickHouse#111993. Co-Authored-By: Claude Fable 5 <[email protected]>
isFromJoinTree pushed JOIN and CROSS JOIN children only, so a column sourced below an ArrayJoinNode got no join side and resolveMatcher skipped its join_use_nulls promotion. A matcher inside a lambda then disagreed with the same matcher at the top level: b1.k stayed UInt64 where SELECT b1.* reports Nullable(UInt64). An ARRAY JOIN is transparent for this question, so descend into its table expression. Also covers the two ARRAY JOIN shapes that were unasserted, wrapped in a subquery and directly on the join tree. Reverting only this traversal reproduces the wrong matcher type; reverting the promotion fix aborts on the matcher statement while the explicit-column oracle passes.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 52/53 (98.11%) · Uncovered code |
CI finish ledger - d3ec18eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
PR-caused gate: ZERO. My diff is a matcher-scope fix in Session id: cron:our-pr-ci-monitor:20260727-073000 |
@groeneai I suppose this can be related to change. Can you reproduce on current and master builds? |
|
@vdimir yes, it reproduces on both, and the fix is now open as #112898. This is the fixing-PR link my CI finish ledger promised for Minimal repro, no fuzzer, no wrapper, no SET enable_analyzer = 1;
CREATE TABLE r1 (a UInt32, v Int16) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE r2 (a UInt64, w UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO r1 VALUES (1, 10);
INSERT INTO r2 VALUES (1, 11);
SELECT w, a, v FROM r1 INNER JOIN r2 USING (a)
PREWHERE ((arrayMap(z -> tuple(* EXCEPT w), [1])[1]).2) != 0;
Root cause: #112898 also does not overlap this PR: the |
Master added scope.in_prewhere (fa59e67, "Do not rewrite IN to a correlated join inside PREWHERE") at the same statement where this branch saves and clears scope.join_use_nulls around the PREWHERE resolution, so the two textually collided. The two flags are independent and both are kept: in_prewhere is read by resolveFunction.cpp to skip the rewrite_in_to_join rewrite, while clearing join_use_nulls keeps PREWHERE columns at their pre-join types because the ReplaceColumnsVisitor rollback below cannot descend into a lambda body.
Master renamed ArrayJoinNode's pointer accessor: getTableExpression() now
returns a const reference to ITableExpressionNode, and the QueryTreeNodePtr
form is getTableExpressionNode(). The merge left the old spelling, which does
not compile ("no member named 'get' in 'DB::ITableExpressionNode'").
Use getTableExpressionNode(), matching the JoinNode branch directly above.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 47ad363Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of the four are caused by this PR's diff ( Session id: cron:our-pr-ci-monitor:20260814-180000 |
|
Dear @vdimir, 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. |
Two conflicts in src/Analyzer/Resolve/QueryAnalyzer.cpp: - isFromJoinTree: master now walks the join tree through collectJoinTreeChildTableExpressions (987a372), which already descends through ARRAY JOIN. This branch's own ARRAY JOIN descent is dropped in favour of master's; the test still covers that case. - resolveUnqualifiedMatcher: master added the preserved-side argument to createProjectionForUsing (b313c9b). Keep it, and keep passing the join-owning scope. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep only the invariants a reader needs at each site: which scope owns `table_expression_node_to_data`, `join_use_nulls` and the PREWHERE rollback map, and why the aggregate scan walks parent scopes. The reasoning behind reading them from the join-owning scope is in the earlier commit messages. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A matcher in a lambda inside a scalar subquery reads the subquery's own columns. `nullable_group_by_keys` compares columns by name and type only, so without the bound the outer query's `GROUP BY x, y WITH ROLLUP` keys match the subquery-local `x`, `y` and the query fails with `NOT_FOUND_COLUMN_IN_BLOCK`. The new case runs the explicit-column form next to the matcher form; removing the bound fails exactly the matcher line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| */ | ||
| auto is_column_from_parent_scope = [&scope](const QueryTreeNodePtr & using_node_from_table) | ||
| /// `table_expression_node_to_data` is populated only on the join-owning scope. | ||
| auto is_column_from_parent_scope = [&nearest_query_scope](const QueryTreeNodePtr & using_node_from_table) |
There was a problem hiding this comment.
PREWHERE disables allow_resolve_from_using only on the query scope, but matcher expansion here still consults the handed-in scope. Lambda scopes created by resolveLambda do not inherit that flag (IdentifierResolveScope copies in_prewhere / resolving_join_on_expression, but not allow_resolve_from_using), so arrayMap(z -> tuple(* EXCEPT w), [1]) inside PREWHERE can still synthesize the merged USING key.
That reintroduces post-join USING semantics specifically for matcher-in-lambda PREWHERE, which changes the key/type seen by the predicate compared with the explicit-column form on FULL/RIGHT JOIN ... USING. I think this block needs the same query-scope treatment as join_use_nulls, or the flag needs to be propagated into child scopes.
The PR workflow run for 8d90a8d was abandoned by the GitHub Actions outage of 2026-10-07 and cannot be re-run from this account. Co-Authored-By: Claude Opus 5.5 <[email protected]>
b13e8f8
Related: #107951
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results and a
LOGICAL_ERROR(Cannot capture column ... because it has incompatible type) when a matcher such asb.*,*,COLUMNS('...')orb.* EXCEPT cappears inside a lambda body. A matcher expanded inside a lambda kept its pre-join column types, sojoin_use_nulls = 1did not turn columns from the NULL side of aLEFT/FULL/RIGHTJOIN intoNullable(unmatched rows produced a value computed over defaults instead ofNULL), andgroup_by_use_nulls = 1withWITH ROLLUP/WITH CUBE/GROUP BY GROUPING SETSfailed withNOT_AN_AGGREGATE. A matcher expanded inside a lambda now carries the same types it would have if the columns were written out explicitly, and a lambda insidePREWHEREis no longer promoted toNullablebyjoin_use_nulls. Also fixed wrong results for a matcher inside a lambda whenanalyzer_compatibility_join_using_top_level_identifier = 1makes aJOIN ... USINGkey resolve to aSELECTprojection alias: the matcher selected the mergedUSINGkey instead of the right table's column.Description
QueryAnalyzer::resolveMatcherapplies both nullability promotions by reading state off the scope it is handed:join_use_nullsiteratesscope.registered_table_expression_nodes, andgroup_by_use_nullslooks matched columns up inscope.nullable_group_by_keys. Both containers are populated only on the query scope that owns the join tree, andIdentifierResolveScope's constructor does not copy either to a child scope. A lambda body is resolved in a fresh child scope, so inside a lambda both promotion blocks were dead code and the matched columns kept their pre-promotion types. Column discovery still worked because it reaches through withscope.getNearestQueryScope()- that asymmetry was the bug. The single-identifier path promotes from the join kind and side it computed while walking the join tree, which is whyb.xworked inside a lambda whileb.*did not.Four bugs are fixed:
join_use_nulls = 1plus a matcher in a lambda over the NULL side of aLEFT/FULLJOIN. This is a wrong-results bug that additionally aborts in debug and sanitizer builds:The unmatched row must produce
[NULL]of typeArray(Nullable(UInt64)), matching the explicit-column formsipHash64(b.x, b.y). Shapes that did not abort silently returned a hash computed over default values instead ofNULL.The same promotion is missing for a
JOIN ... USINGon same-typed keys, where an unqualified matcher inside a lambda over aRIGHTorFULLjoin aborted withCannot capture column 2 ... got Tuple(UInt8, Nullable(UInt64)), but Tuple(UInt8, UInt64) is expected, and is fixed by the same change:group_by_use_nulls = 1plus a matcher in a lambda withWITH ROLLUP,WITH CUBEorGROUP BY GROUPING SETSfailed withCode: 215 NOT_AN_AGGREGATE, because the non-promoted matcher column no longer matched the promoted GROUP BY key:PREWHEREcombined with a JOIN andjoin_use_nulls = 1aborted, with or without a matcher:analyzer_compatibility_join_using_top_level_identifier = 1made aJOIN ... USINGkey resolve to aSELECTprojection alias.resolveUnqualifiedMatchersuppresses the synthetic mergedUSINGkey when the key is absent from a table expression's own columns, but that membership check readtable_expression_node_to_dataoff the scope it was handed, and like the two containers above the map is populated only on the join-owning scope. Inside a lambda the lookup missed, the suppression never fired, and the matcher matched the merged key while the same matcher at the top level did not:Unlike the first three this one is independent of any
Nullablepromotion: it reproduces withjoin_use_nulls = 0as well, where the unmatched row returned[(10)]instead of[(0)]. Reported by the automated reviewer on this pull request.Classifying which side of a join a matched column comes from also has to see through an
ARRAY JOIN. Master now does that inisFromJoinTree(viacollectJoinTreeChildTableExpressions), so this pull request no longer changes it; the test still covers the case, where a matcher in a lambda used to disagree with the same matcher at the top level:Both promotion blocks in
resolveMatchernow read their state from the nearest scope that owns it, bounded at the enclosing QUERY/UNION scope so a lambda in an inner subquery cannot adopt an outer query's join tree or GROUP BY keys. The owning scope is also passed toconvertJoinedColumnTypeToNullIfNeeded, because it records the type change inscope.join_columns_with_changed_typesand thePREWHERErollback reads that map only from the query scope.group_by_use_nullspromotion must not apply to pre-aggregation values, and the block's aggregate guard read the immediate scope only. SinceExpressionsStackis per-scope, an aggregate enclosing a lambda sits on a parent scope's stack, so the guard is now the same cross-scope scanresolveExpressionNodealready uses.join_use_nullsnullability is a property of the join output, so it deliberately has no such guard, andsum(arrayMap(z -> sipHash64(b.*), [1])[1])is promoted.PREWHEREis evaluated storage-side, before the join, so its expressions must keep pre-join types.resolveQueryenforced that by re-resolvingPREWHEREand undoing promotions withReplaceColumnsVisitor, whoseneedChildVisitdoes not descend intoLAMBDA, so the rollback could not reach a lambda body. Rather than deepen the rollback,join_use_nullsis now cleared on the query scope whilePREWHEREis resolved, so the promotion never happens there. This is the same mechanism already used at the USING-column alias site. A subquery nested insidePREWHEREre-reads the setting from its own context, so its own join is unaffected, and case 3 above is fixed by the same change.One related failure is deliberately left out of scope, because it is a different root cause that this change does not touch. A
JOIN ... USINGon differently typed keys retypes the matched column to the supertype increateProjectionForUsing, and that retype is independent ofjoin_use_nulls:need_nullableonly decides whether the type is wrapped inNullable, whilesetColumnTyperuns either way. So an unqualified matcher in aPREWHERElambda still adopts theUSINGsupertype:This fails identically before and after this change, with
join_use_nulls = 0and onINNER JOINas well. The retype cannot simply be skipped, because its entry injoin_columns_with_changed_typesis what redirects theUSINGcolumn to the left table inPREWHERE; a proper fix needs thePREWHERErollback to descend into lambda bodies and to re-resolve the lambda's cached signature, which is a larger change than this one.Test:
tests/queries/0_stateless/04647_matcher_in_lambda_join_use_nulls.sql. Every case asserts values against the equivalent explicit-column query rather than only the absence of an abort, and covers the matcher flavours (*,b.*,COLUMNS,EXCEPT, unaliased table name, nested lambdas), the join kinds,LowCardinalityandArraycolumn types,USINGjoins (including theRIGHT/FULLcorner above, with and withoutPREWHERE), aggregate and window contexts,PREWHEREversusWHERE, a subquery nested inPREWHERE, and the projection-aliasUSINGkey of case 4 under bothjoin_use_nullsvalues with a control that keeps the merged key matching when the compatibility setting is off, and a nullable side that is a subquery containingARRAY JOIN, and both anARRAY JOINwrapped in a subquery and one directly on the join tree, whose columns are reached only by descending through theARRAY JOINwhen classifying the join side, and a subquery-local matcher column under an outerROLLUP, which must not adopt the outerGROUP BYkeys.Found by the AST fuzzer inside the stress test. CI reports:
Stress test (arm_debug): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110127&sha=40ea0f0e62eb09b0e480d458e33b45e54585e517&name_0=PR&name_1=Stress%20test%20%28arm_debug%29Stress test (arm_asan_ubsan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=f53e6fc6ff04e64324e20729e7eb7d3401627894&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29Stress test (amd_asan_ubsan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107582&sha=09ae616ec6fa5ae5f217d9acb4bcd15bec0a5ddd&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29The signature is reported under two stack-trace ids,
STID 3293-4e7fon arm builds andSTID 3293-46faon amd builds. They are the same defect: the ClickHouse frames are identical, differing only in two frames that arm inlines away, the aborting query is byte-identical, and over 40 days every 4e7f hit is arm and every 46fa hit is amd with no crossover. Combined, 9 hits across 9 unrelated pull requests in 40 days.Workflow [PR]
Sync PR [sync-upstream/pr/111993]
Version info
26.10.1.2022-master(included in26.10and later)