Repository navigation
Conversation
…n PREWHERE An unqualified matcher (`*`, `* EXCEPT c`) inside a lambda body in PREWHERE over `JOIN ... USING (k)` expanded to the merged USING key instead of each table's own columns, so the header declared the merged supertype while the read supplied the table's own column and `columnMatchesType` aborted the server with `Unexpected return type from tuple`. The flag that means "you are inside PREWHERE, do not rewrite to the merged key" is set on the query scope only, and `IdentifierResolveScope`'s constructor does not propagate it, so a lambda body resolved in a fresh child scope saw its default. Both rewrite sites reached from `resolveUnqualifiedMatcher` therefore fired: the merged-key substitution and the matched column's retype. Read the flag and register the retype's undo entry on the join-owning scope instead, which is where every other join-state access in that helper already reads from. Registering the undo entry is only effective if something applies it, and the PREWHERE rollback did not descend into a lambda body, so `ReplaceColumnsVisitor` now visits `LAMBDA` and refreshes the lambda's cached result type after its body is rewritten, mirroring `convertNestedGroupByKeysToNullable`. The defect is not wrapper-specific: plain `UInt32` against `UInt64` aborts the same way, and with `String` against `Nullable(String)` the mismatch is inverted. The condition is that the USING supertype differs from the left column's own type. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (click to expand)Two independent reviews of this change before publication: a cold read of the resulting code by a
Session id: cron:clickhouse-review-slot-9:20260801-104300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260801-092400 |
|
cc @novikd @yakov-olkhovskiy, could you review this? |
|
Workflow [PR], commit [1f2486e] Summary: ❌
AI ReviewSummaryThis PR makes unqualified matchers inside lambdas honor the query scope's Final VerdictStatus: ✅ Approve |
The two join_use_nulls cells read only preserved-side columns, so neither could observe a nullable rewrite. Under LEFT JOIN both `a` and `v` come from the preserved left table and stay non-Nullable, and the ON case read `v` from the left side too, so it produced the same row count on either side of the fix. Add RIGHT and FULL shapes, where the left table's `v` is the non-preserved column and the replacement map really carries a `Nullable(Int16)` entry for it, and assert the resolved type through `EXPLAIN QUERY TREE` rather than only a row count. The lambda body must converge on the direct form's `Int16` after the rollback, so the direct form rides along as the oracle. The pre-existing USING cell is kept: it does redden, on the supertype carrier rather than on nullability, which is the only thing a preserved-side shape can assert. Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 18/20 (90.00%) · Uncovered code |
CI finish ledger - 08cba22Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not caused by this PR: #111993 is the fixing PR for that Session id: cron:our-pr-ci-monitor:20260801-190047 |
CI finish ledger - 08cba22Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is terminal on this head (174 check-runs, 0 queued or in progress,
On the overlap with this PR's own scope: this PR's description already records that the Session id: cron:our-pr-ci-monitor:20260801-203000 |
Ergus
left a comment
There was a problem hiding this comment.
With this PR, a lambda matcher there honours the flag, which is the intended behaviour. No test covers it.
| -- join actually widens: under LEFT JOIN both `a` and `v` come from the preserved left table and stay | ||
| -- non-Nullable, which is why the supertype carrier below is the only thing a LEFT shape can assert. | ||
| SELECT 'join_use_nulls with USING'; | ||
| SELECT count() FROM r1 LEFT JOIN r2 USING (a) |
There was a problem hiding this comment.
The new test seeds the fuzzer into a sibling abort. The PREWHERE single-table check skips lambda bodies.
CollectPrewhereTableExpressionVisitor::needChildVisitexcludesLAMBDA.- The fuzzer turns
USING (a)intoON`` orCROSS/PASTE joins. The lambda matcher then expands tor2.a in PREWHERE`, and the right-table column passes the check unseen. - The direct form is rejected correctly. Checked with the local master clickhouse local:
- ...
r1 CROSS JOIN r2 PREWHERE ((tuple(* EXCEPT w)).2) != 0givesILLEGAL_PREWHERE: Invalid column __table2.a in PREWHERE. - ...
PREWHERE ((arrayMap(z -> tuple(* EXCEPT w), [1])[1]).2) != 0givesNOT_FOUND_COLUMN_IN_BLOCK ... tuple(__table1.a, __table1.v, __table2.a). - Fuzzer variants of the lambda form escalate to Cannot capture column (STID 3293-46fa).
- The defect is pre-existing: Fix wrong result and LOGICAL_ERROR for a matcher inside a lambda with join_use_nulls / group_by_use_nulls #111993's own fuzzer run hit it on 2026-07-27 with a PASTE JOIN shape. This PR's test makes it reachable in every Stress and AST fuzzer run, so after merge it will recur on unrelated PRs.
- The PR's own contract is that the lambda form expands exactly like the direct form, so this sibling is in scope.
Fix:
in that visitor, descend into LAMBDA and skip columns whose source is a LambdaNode. Add the CROSS JOIN and ON lambda cells above with -- { serverError ILLEGAL_PREWHERE }.
There was a problem hiding this comment.
Thanks, done.
CollectPrewhereTableExpressionVisitornow descends intoLAMBDAand skips columns whose source is the lambda's arguments (LAMBDA_ARGS) (5962194). The CROSS JOIN, ON and PASTE JOIN lambda cells are in 04683 with-- { serverError ILLEGAL_PREWHERE }; without the visitor change the CROSS JOIN cell fails withNOT_FOUND_COLUMN_IN_BLOCK.getPrewhereTableExpressioninAnalyzer/Utils.cpp(shardedGLOBAL JOIN) skipped lambdas the same way, so a right-side PREWHERE inside a lambda kept theGLOBAL RIGHT JOINon the initiator while the direct form was sent to the shards. It descends too now, and 05194 pins that both plans agree (c1ffd7b).- As with the direct form, a lambda that reads only a right-side column now gets PREWHERE on that side (
PREWHERE r2.w != 0already does); master fails it withNOT_FOUND_COLUMN_IN_BLOCK. Check PREWHERE column support inside lambda bodies #114721 made the same visitor change and was closed as not to be supported. If you would rather refuse this case, I will.
I merged master, because the fix has to change 04647, which only exists there:
- 04647 section 12e (Fix wrong result and LOGICAL_ERROR for a matcher inside a lambda with join_use_nulls / group_by_use_nulls #111993) compared the lambda matcher with explicit columns of the merged key, which agreed only because of this bug. Its oracle is now the same matcher written directly in PREWHERE; the selected rows are unchanged.
- PREWHERE is now resolved with
join_use_nullsdisabled, so the RIGHT/FULLjoin_use_nullscells I added in August pass on master and without the lambda descent inReplaceColumnsVisitor. I removed them.
On the review summary: the only other place that clears the flag on master is the JOIN USING alias probe (#123103). A lambda there is not observable: getExpressionSource refuses any expression that holds a lambda, so arrayMap(z -> tuple(*), [1]) AS k ... USING (k) is Code: 47 with and without this PR, for a qualified matcher and over a single JOIN as well. If you meant another place, tell me which and I will add the test.
`CollectPrewhereTableExpressionVisitor` did not descend into `LAMBDA`, so a column read only inside a lambda body escaped the check that PREWHERE reads one table. Once an unqualified matcher in a lambda expands like the direct one, `CROSS JOIN`, `JOIN ... ON` and `PASTE JOIN` put the right table's columns there, and the query failed later with `NOT_FOUND_COLUMN_IN_BLOCK` or a `Cannot capture column` logical error instead of `ILLEGAL_PREWHERE`. Lambda parameters are skipped by their `LAMBDA_ARGS` source, as `CollectSourceColumnsVisitor` does. 04647 section 12e compared a lambda matcher in PREWHERE with explicit columns of the merged USING key, which the lambda form matched only because of the scope bug fixed in this PR. Its oracle is now the same matcher written directly in PREWHERE. In 04683 the expansion under `analyzer_compatibility_join_using_top_level_identifier` follows master after ClickHouse#123103. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`getPrewhereTableExpression`, which decides whether a sharded `GLOBAL JOIN` is rewritten and whether PREWHERE moves into the broadcast subquery, skipped lambda bodies too. A PREWHERE that reads the right table only inside a lambda was treated as columnless, so the `GLOBAL RIGHT JOIN` stayed on the initiator while the same predicate without the lambda is sent to the shards. 05194 now pins that the two plans agree. Since PREWHERE is resolved with `join_use_nulls` disabled, the 04683 cells that read a non-preserved column under `join_use_nulls` pass on master and without the lambda descent of `ReplaceColumnsVisitor`, so they are removed. 04683 also covers `PASTE JOIN` and a lambda that reads only the right table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
The PREWHERE rollback (`ReplaceColumnsVisitor`) gives the columns of a JOIN USING
key back their pre-join types and re-resolves the functions above them, but a
higher-order function kept its lambdas bound to the supertype. When the rolled-back
expression feeds a lambda, the lambda parameter and the array element disagree:
SELECT count() FROM r1 INNER JOIN r2 USING (a)
PREWHERE arrayMap(t -> t.2, arrayMap(z -> tuple(* EXCEPT w), [1]))[1] != 0;
-- Logical error: 'Cannot capture column 2 because it has incompatible type:
-- got Tuple(UInt32, Int16, UInt32), but Tuple(UInt64, Int16, UInt64) is expected.'
The same happens on master with a direct matcher,
`PREWHERE arrayMap(t -> t.2, [tuple(* EXCEPT w)])[1] != 0`.
Now a higher-order function recomputes the parameter types of its lambdas with
`getLambdaArgumentTypes` from its rewritten arguments and visits the lambda bodies
after that, so the parameters, the body and the lambda type follow the rolled-back
input. Reported by the AI review on ClickHouse#112898.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 1f2486eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261022-183007 |
Related: #111993
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a
LOGICAL_ERROR(Unexpected return type from tupleorCannot capture column) when an unqualified matcher such as*or* EXCEPT cappears inside a lambda body inPREWHEREover aJOIN ... USING (k)whose merged key type differs from the left table's ownk, or is the input of another lambda. Such a matcher now expands like the same matcher written directly inPREWHERE, and a lambda inPREWHEREthat reads a column of another table is rejected withILLEGAL_PREWHERE.Description
On 26.8,
SELECT w, a, v FROM r1 INNER JOIN r2 USING (a) PREWHERE ((arrayMap(z -> tuple(* EXCEPT w), [1])[1]).2) != 0fails withUnexpected return type from tuplewhenr1.aisUInt32andr2.aisUInt64. Found byAST fuzzer (amd_debug, targeted, old_compatibility), STID3262-472c, on #111993 (CI report).The flag that keeps
PREWHEREfrom rewriting a matched column to the mergedUSINGkey is set on the query scope, and a lambda body resolves in a fresh child scope that did not see it. The flag is now read, and the retype's undo entry registered, on the join-owning scope.ReplaceColumnsVisitorbinds a lambda's parameters again from the rolled-back arguments of its function before visiting the body (PREWHERE arrayMap(t -> t.2, [tuple(* EXCEPT w)])[1] != 0failed withCannot capture columnon 26.8).CollectPrewhereTableExpressionVisitorskipped lambda bodies, so withCROSS JOIN,JOIN ... ONorPASTE JOINa lambda matcher put the right table's columns inPREWHEREunchecked, failing withNOT_FOUND_COLUMN_IN_BLOCKorCannot capture column(STID3293-46fa). It now checks lambda bodies and skips lambda parameters, andgetPrewhereTableExpression(shardedGLOBAL JOIN) does the same. A lambda reading only a right-side column now putsPREWHEREon that side, likePREWHERE r2.w != 0.04647 (#111993) section 12e compared the lambda matcher with explicit columns of the merged key, which agreed only because of this bug; its oracle is now the direct matcher.
On a debug build of master with this branch merged, 04683, 04647 and 05194 pass and fail on master, removing the visitor change or the parameter rebinding reddens the new cells, and 67 other
PREWHEREtests with lambdas give identical output.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/112898]