Skip to content

Fix wrong result and LOGICAL_ERROR for a matcher inside a lambda with join_use_nulls / group_by_use_nulls - #111993

Merged
alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-3293-4e7f-lambda-qualified-asterisk-jun
Oct 10, 2026
Merged

alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-3293-4e7f-lambda-qualified-asterisk-jun

Conversation

@groeneai

@groeneai groeneai commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107951

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 wrong results and a LOGICAL_ERROR (Cannot capture column ... because it has incompatible type) when a matcher such as b.*, *, COLUMNS('...') or b.* EXCEPT c appears inside a lambda body. A matcher expanded inside a lambda kept its pre-join column types, so join_use_nulls = 1 did not turn columns from the NULL side of a LEFT/FULL/RIGHT JOIN into Nullable (unmatched rows produced a value computed over defaults instead of NULL), and group_by_use_nulls = 1 with WITH ROLLUP / WITH CUBE / GROUP BY GROUPING SETS failed with NOT_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 inside PREWHERE is no longer promoted to Nullable by join_use_nulls. Also fixed wrong results for a matcher inside a lambda when analyzer_compatibility_join_using_top_level_identifier = 1 makes a JOIN ... USING key resolve to a SELECT projection alias: the matcher selected the merged USING key instead of the right table's column.

Description

QueryAnalyzer::resolveMatcher applies both nullability promotions by reading state off the scope it is handed: join_use_nulls iterates scope.registered_table_expression_nodes, and group_by_use_nulls looks 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 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 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.

Four bugs are fixed:

  1. join_use_nulls = 1 plus a matcher in a lambda over the NULL side of a LEFT/FULL JOIN. This is a wrong-results bug that additionally aborts in debug and sanitizer builds:
SELECT arrayMap(z -> sipHash64(b.*), [1]) FROM t1 LEFT JOIN t2 AS b ON t1.a = b.x SETTINGS join_use_nulls = 1;

The unmatched row must produce [NULL] of type Array(Nullable(UInt64)), matching the explicit-column form sipHash64(b.x, b.y). Shapes that did not abort silently returned a hash computed over default values instead of NULL.

The same promotion is missing for a JOIN ... USING on same-typed keys, where an unqualified matcher inside a lambda over a RIGHT or FULL join aborted with Cannot capture column 2 ... got Tuple(UInt8, Nullable(UInt64)), but Tuple(UInt8, UInt64) is expected, and is fixed by the same change:

SELECT arrayMap(z -> tuple(* EXCEPT w), [1]) FROM p1 RIGHT JOIN p2 USING (a) SETTINGS join_use_nulls = 1;
  1. group_by_use_nulls = 1 plus a matcher in a lambda with WITH ROLLUP, WITH CUBE or GROUP BY GROUPING SETS failed with Code: 215 NOT_AN_AGGREGATE, because the non-promoted matcher column no longer matched the promoted GROUP BY key:
SELECT x, y, arrayMap(z -> sipHash64(t3.*), [1]) FROM t3 GROUP BY x, y WITH ROLLUP SETTINGS group_by_use_nulls = 1;
  1. An expression containing a lambda in PREWHERE combined with a JOIN and join_use_nulls = 1 aborted, with or without a matcher:
SELECT count() FROM m1 RIGHT JOIN m2 AS b ON m1.a = b.x
PREWHERE arrayMap(z -> sipHash64(m1.a), [1])[1] > 0 SETTINGS join_use_nulls = 1;
  1. A matcher in a lambda selected the wrong column when analyzer_compatibility_join_using_top_level_identifier = 1 made a JOIN ... USING key resolve to a SELECT projection alias. resolveUnqualifiedMatcher suppresses the synthetic merged USING key when the key is absent from a table expression's own columns, but that membership check read table_expression_node_to_data off 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:
SELECT a + 1 AS id, arrayMap(z -> tuple(* EXCEPT a), [1]) AS matcher
FROM (SELECT 1 AS a UNION ALL SELECT 9 AS a) AS q1
FULL JOIN (SELECT 2 AS id) AS q2 USING (id)
SETTINGS join_use_nulls = 1, analyzer_compatibility_join_using_top_level_identifier = 1;
-- unmatched row returned [(10)]; the top-level matcher returns NULL

Unlike the first three this one is independent of any Nullable promotion: it reproduces with join_use_nulls = 0 as 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 in isFromJoinTree (via collectJoinTreeChildTableExpressions), 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:

SELECT toTypeName(arrayMap(z -> tuple(b1.*), [1])) FROM b1 ARRAY JOIN b1.arr
RIGHT JOIN b2 ON b1.k = b2.k SETTINGS join_use_nulls = 1;
-- Array(Tuple(UInt64, Array(UInt64))), while `SELECT b1.*` reports k as Nullable(UInt64)

Both promotion blocks in resolveMatcher 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 also 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. Since ExpressionsStack is per-scope, an aggregate enclosing a lambda sits on a parent scope's stack, so 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, and sum(arrayMap(z -> sipHash64(b.*), [1])[1]) is promoted.

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 is the same mechanism already used at the USING-column alias site. A subquery nested inside PREWHERE re-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 ... USING on differently typed keys retypes the matched column to the supertype in createProjectionForUsing, and that retype is independent of join_use_nulls: need_nullable only decides whether the type is wrapped in Nullable, while setColumnType runs either way. So an unqualified matcher in a PREWHERE lambda still adopts the USING supertype:

-- p1.a is UInt8, p2.a is Int64
SELECT count() FROM p1 LEFT JOIN p2 USING (a)
PREWHERE arrayMap(z -> tuple(* EXCEPT w), [1])[1].1 >= 0 SETTINGS join_use_nulls = 1;
-- Unexpected return type from tuple. Expected Tuple(Int64, UInt64). Got Tuple(UInt8, UInt64)

This fails identically before and after this change, with join_use_nulls = 0 and on INNER JOIN as well. The retype cannot simply be skipped, because its entry in join_columns_with_changed_types is what redirects the USING column to the left table in PREWHERE; a proper fix needs the PREWHERE rollback 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, LowCardinality and Array column types, USING joins (including the RIGHT/FULL corner above, with and without PREWHERE), aggregate and window contexts, PREWHERE versus WHERE, a subquery nested in PREWHERE, and the projection-alias USING key of case 4 under both join_use_nulls values with a control that keeps the merged key matching when the compatibility setting is off, and a nullable side that is a subquery containing ARRAY JOIN, and both an ARRAY JOIN wrapped in a subquery and one directly on the join tree, whose columns are reached only by descending through the ARRAY JOIN when classifying the join side, and a subquery-local matcher column under an outer ROLLUP, which must not adopt the outer GROUP BY keys.

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%29
Stress 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%29
Stress 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%29

The signature is reported under two stack-trace ids, STID 3293-4e7f on arm builds and STID 3293-46fa on 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

  • Merged into: 26.10.1.2022-master (included in 26.10 and later)

groeneai and others added 4 commits July 26, 2026 16:30
…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent reviewer model and an automated review gate examined this change before it was
opened, over four fix rounds. Both blockers found are fixed here; the findings and their
adjudication are below.

# Finding Verdict
❌ PREWHERE + JOIN ... USING: the merged-key projection read promotion state from the lambda scope. resolveUnqualifiedMatcher passed the handed scope to createProjectionForUsing, so a lambda child re-read join_use_nulls from its own context and recorded its type change in a rollback map the PREWHERE rollback never consults. ❌ AGREE, fixed. QueryAnalyzer.cpp:2241 now passes *nearest_query_scope. Measured: the pre-fix build returned 1 of 2 rows for the pre-join-type assertion and 2 of 2 for the promoted-type assertion, inverting to 2 / 1 after the fix. Reverting the one-liner alone rebuilds to a Build ID bit-identical to the pre-fix binary and breaks exactly the two FULL JOIN assertions of test case 12e, with the other 146 reference lines byte-identical.
❌ The regression test carried no SET enable_analyzer = 1. All 42 toTypeName() assertions describe new-analyzer output and the whole fix is in src/Analyzer/, which is inert at enable_analyzer = 0, yet two old-analyzer stateless jobs run on every pull request (ci/defs/job_configs.py:706 and :719, in the group ci/workflows/pull_request.py:117 includes) and tests/clickhouse-test:2054 falls back to the plain .reference because no .oldanalyzer.reference exists. ❌ AGREE, fixed. Measured on a real old-analyzer server with the same binary: FAIL before the pin (wrong types in section 12d, Array(Tuple(Nullable(UInt8), Nullable(UInt64))) where the reference has Array(Tuple(UInt8, Nullable(UInt64)))), OK after. So the test would have gone red on those jobs rather than merely running vacuously. Pinned rather than tagged no-old-analyzer, which would have skipped the test there and discarded the coverage. analyzer.xml declares no <constraints>, so a session SET overrides the profile. The .reference is byte-identical.
💡 The PR description could attribute the USING + RIGHT/FULL repair explicitly to the scope fix rather than to the PREWHERE change. 💡 DISAGREE. The description already says that case "is fixed by the same change" as the first bug, with its reproducer inline, and the Test paragraph already names the RIGHT/FULL corner "with and without PREWHERE". Nothing in it claims the repair is a PREWHERE effect.
💡 A projection alias referenced from PREWHERE could be frozen unpromoted in the resolution memo, since under group_by_use_nulls the projection resolves after PREWHERE. 💡 DISAGREE (raised and refuted during review). resolveGroupByNode clears the memo and the identifier cache whenever nullable_group_by_keys is non-empty (QueryAnalyzer.cpp:4067), which holds for every query with at least one GROUP BY key. The only case where that set is empty is a grouping-sets form with no keys, where a non-aggregate projection expression fails NOT_AN_AGGREGATE before a wrong value can be produced.

Noted, not blocking: the unguarded join_use_nulls save and restore around the PREWHERE resolve
follows the pre-existing allow_resolve_from_using toggle two lines above, and no try/catch
sits between that block and the caller. Test number 04647 is shared with an existing test name,
which the style check permits (it reports numbering gaps, not collisions).

Session id: cron:clickhouse-review-slot-11:20260726-223253

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no fuzzer and no randomization. CREATE TABLE t1 (a UInt64) ENGINE=Memory; CREATE TABLE t2 (x UInt64, y UInt64) ENGINE=Memory; SELECT arrayMap(z -> sipHash64(b.*), [1]) FROM t1 LEFT JOIN t2 AS b ON t1.a=b.x SETTINGS join_use_nulls=1; aborts on master (Logical error: 'Cannot capture column 2 because it has incompatible type: got Nullable(UInt64), but UInt64 is expected.', ColumnFunction.cpp:383) and returns values with the fix.
b Root cause explained? Yes. QueryAnalyzer::resolveMatcher reads both nullability promotions off the scope it is handed: join_use_nulls iterates scope.registered_table_expression_nodes, group_by_use_nulls reads scope.nullable_group_by_keys. Neither container is copied to a child scope, and a lambda body resolves in a fresh child scope, so inside a lambda both blocks are dead code and the matched columns keep pre-promotion types. Column discovery still works because it reaches through with scope.getNearestQueryScope() - that asymmetry is the bug. ActionsDAG::updateHeader then binds the JOIN's promoted Nullable header column by name to the non-Nullable input node and the capture's type check fires. The single-identifier path promotes from the join walk instead, which is why b.x worked inside a lambda while b.* did not.
c Fix matches root cause? Yes. Both promotion blocks now consult the scope that owns the state, bounded at the enclosing QUERY/UNION scope, and the owning scope is passed to convertJoinedColumnTypeToNullIfNeeded so its rollback entry lands where the PREWHERE rollback reads it. No guard at the abort site, no widened bounds, no no-random-* tag. Downgrading the appendArgument LOGICAL_ERROR and coercing types in ActionsDAG::updateHeader were both rejected as wrong-layer: this is valid SQL that must return a specific result, so the analyzer is where the type is wrong.
d Test intent preserved / new tests added? Yes. New 04647_matcher_in_lambda_join_use_nulls.sql (165 reference lines); no existing test removed or weakened. Every case asserts values and types against the equivalent explicit-column query rather than only the absence of an abort. Seven mutation tests prove the assertions are live: reverting Fix A breaks case 1, reverting Fix B's key walk breaks case 10, reverting only Fix B's cross-scope aggregate guard breaks case 11, removing Fix C breaks case 12, making join_use_nulls blanket-inherited breaks case 12c and nothing else, reverting Fix A alone breaks exactly the four matcher statements of case 12d (USING + RIGHT/FULL) while their oracles and the join_use_nulls = 0 / LEFT JOIN controls keep passing, and reverting the USING-projection scope fix alone breaks exactly the two FULL JOIN type assertions of case 12e and nothing else. Cases 12d and 12e were driven statement by statement against a current-master binary, because the file aborts at case 1 on master and a whole-file diff would mask everything below it. The test pins SET enable_analyzer = 1, because all 42 toTypeName() assertions describe new-analyzer output and three CI jobs run the old analyzer; measured on a real old-analyzer server, without the pin the case 12d type assertions fail and with it the test passes. Pinning keeps the coverage on those jobs, where a no-old-analyzer tag would have discarded it.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (6977fd388472b8fe54e9990f6fa4f1633a5f8f45 vs the master snapshot). Every case in the test was measured on both: the join cases, the aggregate and window cases and the nested-subquery-in-PREWHERE case abort on master and match their explicit-column oracle with the fix; the group_by_use_nulls + ROLLUP/CUBE/GROUPING SETS cases return NOT_AN_AGGREGATE on master; the control cases (RIGHT, INNER, CROSS, join_use_nulls=0, USING, matcher without a lambda, the APPLY aggregate carve-out, PREWHERE with a matcher) are byte-identical before and after. EXPLAIN QUERY TREE run_passes=1 directly shows the lambda body's column nodes changing to Nullable(UInt64).
f Fix is general across code paths? Yes. The fix is inside resolveMatcher/resolveUnqualifiedMatcher, so all three sites that create a lambda child scope (resolveFunction.cpp:1597, resolveFunction.cpp:1925, and the APPLY column transformer) are covered by construction, and nested lambdas traverse arbitrarily many scopes. createProjectionForUsing has one other caller, the identifier path at IdentifierResolver.cpp:1364; I measured it rather than assuming it safe, and a bare USING key inside a PREWHERE lambda is correct there both before and after this change, because tryResolveIdentifierInParentScopes recurses with *scope.parent_scope so that caller already holds the join-owning query scope. The correlated-column logic that deliberately relies on scope-locality is untouched and pinned by tests. A matcher inside INTERPOLATE is a syntax error, and a matcher in a column DEFAULT/ALIAS expression is rejected by the server on master and with the fix alike, so neither is a reachable carrier and no speculative code was added for them.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Type wrappers: UInt64 promoted, LowCardinality(String) promoted to LowCardinality(Nullable(String)), Array(UInt64) correctly left alone by the existing JoinCommon::canBecomeNullable gate. Join kinds LEFT, FULL, RIGHT, INNER, CROSS and USING, including the USING + PREWHERE intersection where only FULL JOIN merges both key arguments and so is the only kind whose merged key can be promoted. Matcher flavours *, b.*, COLUMNS('x'), b.* EXCEPT y, unaliased t2.*. Settings matrix join_use_nulls 0/1 and group_by_use_nulls 0/1 crossed with ROLLUP, CUBE and GROUPING SETS. Contexts: bare projection, aggregate argument, window function, subquery, nested lambda, WHERE, PREWHERE, and a subquery nested in PREWHERE. Both the matched row and the unmatched (NULL) row are asserted for every shape.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no changed default, no format or serialization change, so no SettingsChangesHistory.cpp entry is required. The behaviour change is bug-for-correct: queries that aborted now return values, and queries that returned a hash computed over default values for unmatched rows now return NULL, which matches the explicit-column form and the documented join_use_nulls semantics. This is stated in the changelog entry.
i Invariants and contracts preserved? Yes. join_columns_with_changed_types rollback entries now land in the query scope, the only scope the PREWHERE rollback reads, instead of being silently dropped into a lambda scope. The "expressions in PREWHERE with JOIN should not change their type" invariant is now established by prevention rather than by a rollback that could not descend into a lambda. A nested subquery keeps its own join_use_nulls. The pre-aggregation invariant for group_by_use_nulls keys is preserved across a lambda scope boundary, while join_use_nulls deliberately has no aggregate guard because it is a property of the join output. join_use_nulls is saved and restored around the PREWHERE resolve on every path of that block, following the adjacent allow_resolve_from_using pattern. The scope walk returns the first scope with a non-empty container, so a given JoinNode is processed exactly once.

Also verified: 50/50 randomized runs of the new test pass, and a targeted sweep of 646 existing tests matching join_use_nulls, group_by_use_nulls, APPLY, COLUMNS(, WITH ROLLUP, WITH CUBE, GROUPING SETS or PREWHERE shows no regression: every failure in my sandbox reproduces identically with the unmodified master binary (missing second replica, absent s3_cache storage policies, absent named collections, no ZooKeeper), and the single test that differed is a sandbox flake that is flakier on master than with this change and contains no matcher, lambda or JOIN.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @yakov-olkhovskiy — could you review this? QueryAnalyzer::resolveMatcher read both nullability promotions off the scope it was handed, but neither registered_table_expression_nodes nor nullable_group_by_keys is copied to a child scope, so inside a lambda body both promotion blocks were dead code and a matcher like b.* kept its pre-join types while the explicit b.x did not.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8d90a8d]

Summary: ✅


AI Review

Summary

This PR fixes the main matcher-in-lambda regressions by making resolveMatcher re-read join/grouping metadata from the query-owning scope, by fixing the JOIN ... USING projection-alias membership check, and by adding broad stateless coverage. I still do not think it is ready to approve, because PREWHERE only disables allow_resolve_from_using on the query scope: an unqualified matcher resolved inside a lambda can still synthesize the merged USING key and observe post-join semantics on the exact PREWHERE path this PR is trying to make pre-join.

Findings

⚠️ Majors

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:2769] resolveUnqualifiedMatcher still gates JOIN ... USING synthesis on the handed-in scope.allow_resolve_from_using. PREWHERE flips that flag only on the query scope (src/Analyzer/Resolve/QueryAnalyzer.cpp:7502-7513), but lambda child scopes created by resolveLambda do not inherit it, so arrayMap(z -> tuple(* EXCEPT w), [1]) inside PREWHERE can still resolve through the merged USING key instead of the pre-join table columns. On FULL/RIGHT JOIN ... USING with differently typed keys this keeps the old post-join supertype/type-mismatch behavior that the PR description explicitly leaves out of scope, so matcher-in-lambda PREWHERE still diverges from the explicit-column form on the same resolver contract. Suggested fix: either propagate the temporary allow_resolve_from_using = false into lambda child scopes while PREWHERE is being resolved, or make this branch consult the nearest query scope's flag the same way the later createProjectionForUsing call already consults the query-owning scope.
Tests
  • ⚠️ Add one focused stateless case for FULL/RIGHT JOIN ... USING with different key types inside a PREWHERE lambda matcher (for example * EXCEPT w). Section 12e currently pins only same-typed USING keys, so this still-broken branch can stay green.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: make matcher resolution inside PREWHERE lambdas honor the query-scope allow_resolve_from_using = false behavior, and add a focused stateless regression case for the mismatched-USING-type variant.

LLVM Coverage Report

Measured on commit 83de118.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.80% 79.70% -0.10%

Changed lines: Changed C/C++ lines covered: 52/53 (98.11%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
groeneai and others added 2 commits July 27, 2026 01:43
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.
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 52/53 (98.11%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d3ec18e

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Unexpected return type from tuple (STID 3262-472c) pre-existing trunk bug, NOT PR-caused - constant folding of tuple(...) during PREWHERE header computation keeps a LowCardinality wrapper the node's declared result_type has stripped (abort at ActionsDAG.cpp:1291 columnMatchesType). Verified byte-identical abort on a pristine master snapshot binary and on this PR head (both RC=134), with identical stack frames. a fix task is created (investigating at full effort - fixing-PR link to follow here)

Mergeable Check is green on this head. The remaining PR rollup red is the aggregate of the
single AST fuzzer line above, not a separate failure.

PR-caused gate: ZERO. My diff is a matcher-scope fix in QueryAnalyzer.cpp plus one stateless
test; it cannot produce the tuple constant-folding wrapper mismatch, which reproduces on master
without the diff.

Session id: cron:our-pr-ci-monitor:20260727-073000

@vdimir

vdimir commented Jul 29, 2026

Copy link
Copy Markdown
Member

AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Unexpected return type from A. Expected B. Got C (STID: 3262-472c) FAIL cidb

@groeneai I suppose this can be related to change. Can you reproduce on current and master builds?

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

@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 AST fuzzer (amd_debug, targeted, old_compatibility) STID 3262-472c. That ledger line's reason column was wrong and I am correcting it here: I described the defect as LowCardinality-wrapper-specific, which it is not.

Minimal repro, no fuzzer, no wrapper, no join_use_nulls:

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;

Unexpected return type from tuple. Expected Tuple(UInt64, Int16). Got Tuple(UInt32, Int16), on a debug build of pristine master at this PR's merge-base and on this PR's head alike, byte-identical message and stack. The real condition is only that the USING supertype differs from the left column's own type, so a plain UInt32/UInt64 pair is enough; with String against Nullable(String) the mismatch is inverted. A LowCardinality-shaped fix would have missed the integer carrier.

Root cause: allow_resolve_from_using is set on the query scope and IdentifierResolveScope's constructor does not propagate it, so a matcher inside a lambda body sees the default true and gets rewritten to the merged USING key even in PREWHERE. Independent of this PR's diff, which is why it reproduces without it.

#112898 also does not overlap this PR: the ON / join_use_nulls channel is promoted at a third site, resolveMatcher's loop, which this PR handles and #112898 does not.

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.
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 8d90a8d38340c0b13153fd54df893715f6e935b4 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 47ad363

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: A is not a table expression (STID 3981-42df) pre-existing fuzzer family, 4 master hits and 24 distinct PRs in 30d #113400 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Unexpected return type from A (STID 3262-419f) pre-existing family, 2 master hits and 68 distinct PRs in 30d #112898 (mine, open)
Stress test (arm_asan_ubsan) / Logical error: ReadFromMergeTree step is expected to be created by readFromParts (STID 3215-370f) pre-existing, also seen on unrelated PR #110910 #110929 (mine, open)
AST fuzzer (amd_debug) / Logical error: Can't determine table for parallel replicas (STID 3634-43a0) pre-existing family, 1 master hit and 42 distinct PRs in 30d #110020 (mine, open)
Sync - CH Inc sync (private, not actionable)

None of the four are caused by this PR's diff (QueryAnalyzer.cpp plus one new stateless test).

Session id: cron:our-pr-ci-monitor:20260814-180000

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

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.

groeneai and others added 3 commits October 7, 2026 13:55
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)

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.

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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit b13e8f8 Oct 10, 2026
300 of 301 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
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 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.

4 participants