Repository navigation
Fix Unexpected return type when a lambda argument shadows an outer column - #121230
alexey-milovidov wants to merge 32 commits into
Conversation
…column
`PlannerActionsVisitorImpl::visitColumn` registered every column it visits as an `INPUT` at every
level of the actions stack, including a lambda scope that declares an argument of the same name.
Inside a lambda body such an `INPUT` *is* the argument: that is how the capture loop of
`visitLambda` tells arguments apart from captured columns. Arguments are created lazily, by the
first reference to the name, so whenever the outer column was visited first it created the argument
and gave it the outer column's type, and the body was then built for a type the argument does not
have. Only the operand order decides it:
CREATE TABLE t (value UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (10);
SELECT value FROM t PREWHERE arrayMap(value -> value + toUInt8(t.value), [1])[1] = 11;
-- 10
SELECT value FROM t PREWHERE arrayMap(value -> toUInt8(t.value) + value, [1])[1] = 11;
-- Logical error: 'Unexpected return type from plus. Expected UInt64. Got UInt16.'
`PREWHERE` reaches this path because it does not use column identifiers as action node names, so
the table column keeps the bare name `value`. The synthetic column of an `INTERPOLATE` expression
has no column identifier at all and takes the same path, which is how the server AST fuzzer hit it
on `master`:
SELECT number, toUInt64(10) AS value FROM numbers(1)
ORDER BY number WITH FILL FROM 0 TO 2
INTERPOLATE (value AS (moduloOrNull(value, 1) AS d) + arrayMap(value -> d + value, [1])[1]);
Now a column whose name collides with an argument of the lambda scope is registered only under the
disambiguated name that the collision path already builds for it.
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=710b4aa8c2e3560c254be50321f6c3be0a1be7df&name_0=MasterCI&name_1=Stress%20test%20%28arm_release%29
Test `05233_lambda_argument_shadowed_column_visit_order`.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [e9e0b6e] Summary: ❌
AI ReviewSummaryThe PR separates shadowed outer columns from lambda arguments, shares action naming with its consumers, and rejects correlated columns in Missing context / blind spots
Findings❌ Blockers
💡 Nits
Tests
Final VerdictStatus: ❌ Block Preserve source identity through constant-column registration and grouped-expression reuse, and add the two focused regression cases. |
…umn-in-lambda-body
…argument `visitCorrelatedColumn` registered the correlated column as a bare `INPUT` in every lambda scope, so in `PREWHERE` (which does not use column identifiers as action node names) a lambda argument of the same name was created with the outer column's type, and planning threw `Unexpected return type from plus`. Now, when a lambda scope on the stack declares an argument of the same name, the column is passed through inner scopes under a disambiguated name that resolves to an alias of the placeholder. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+31.98 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units9 translation units recompiled, 33 s compile time in total, 9 of them have a recent master baseline. |
…ested lambdas under a disambiguated name
When a lambda nested inside the shadowing lambda had already referenced the
outer lambda argument, `visitColumn` registered the outer column under the bare
name in the nested scope, reused the argument node there and aliased the
disambiguated name to it, so the body captured the wrong source and type:
SELECT value FROM t PREWHERE arrayMap(value -> arrayMap(y -> value + t.value, [1])[1], [1])[1] = 11;
Now, when any lambda on the stack declares the column's name as an argument,
the column is passed through every lambda scope under the disambiguated name,
and only the outermost (non-lambda) scope keeps the real INPUT with an alias.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umn-in-lambda-body
…a in a nested lambda Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The remaining red jobs ( This push also merges |
|
🕵 Merged The failing query was The fix takes the |
…her in a lambda in `PREWHERE` A matcher inside a lambda in `PREWHERE` took the `USING` column through `createProjectionForUsing` with the join kind changed to `Left`. That still converted the column to the common `USING` type, which the rollback of `PREWHERE` cannot undo inside a lambda, so a key of a different type threw `Unexpected return type from tuple` (also found by the AST fuzzer). With nested `USING` joins the left argument was `firstNonDefault` of both inner tables, so `PREWHERE` read the right table and threw `ILLEGAL_PREWHERE`. Now take the first argument of the `USING` column, which is the column of the leftmost table even for nested joins, and restore its original type from `join_columns_with_changed_types`, as the rollback does for an identifier. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121230&sha=132b5c0649e27dec1bd97003aa5f395db12a2b73&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 PR: #121230 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umn-in-lambda-body
…PREWHERE` from the left table expression The first argument of the `USING` column of an outer join is the already resolved key of the inner join, which is the column of the right table for an inner `RIGHT JOIN`. Combined with the other columns of the matcher from the left table, `PREWHERE` saw two tables. Take the key from the columns already matched in the left table expression instead; they are resolved by the same rule, so the key is the column of the leftmost table that has it. In `PREWHERE` these columns are not widened to the type of the `USING` key, so they keep their storage types. Apply the same when the right side of a `SEMI`/`ANTI` join is hidden by `semi_join_include_columns_from_both_sides = 0` or `anti_join_include_columns_from_both_sides = 0`, which previously went through `createProjectionForUsing` and produced `firstNonDefault` of the columns of both tables of an inner `FULL JOIN`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/121230/8aa32c9c033f2498fcc5f506a1373742254a412d/pr/ast_fuzzer_amd_release_oracle/job.log (TLP oracle mismatch on |
|
This is the pre-existing In this run It reproduces on master SET enable_full_text_index = 1;
CREATE TABLE tab (id UInt64, lc LowCardinality(Nullable(String)), INDEX idx_lc lc TYPE text(tokenizer = splitByNonAlpha)) ENGINE = MergeTree ORDER BY id;
INSERT INTO tab SELECT number, if(number % 50 = 0, NULL, concat('w', toString(number % 7), ' v', toString(number % 300))) FROM numbers(3000);
SELECT count() FROM tab WHERE NOT hasToken(lc, 'v299') SETTINGS query_plan_direct_read_from_text_index = 1; -- 2990; 2930 with query_plan_direct_read_from_text_index = 0#113332 (by @ Ergus, approved by @ ahmadov) restores the |
…PREWHERE` The previous commit skipped `updateMatchedColumnsFromJoinUsing` for every matcher in `PREWHERE`, including one directly in `PREWHERE` rather than in a lambda. There `allow_resolve_from_using` is disabled, so the `USING` handling is not reached and the matcher keeps the columns of both tables; without the widening, the `PREWHERE` rollback of the changed types did not replace the column of the right table, and `SELECT a FROM l FULL JOIN r USING (a) PREWHERE tuple(*).1 = 9` failed with `ILLEGAL_PREWHERE`. Skip the widening only in a lambda, where `allow_resolve_from_using` is enabled, and add the top-level cases to the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umn-in-lambda-body
|
🕵 Merged |
|
🕵 Merged |
|
🕵 Merged |
A column shadowed by a lambda argument reached the lambda body under a disambiguated name, but `ActionNodeNameHelper` still built the names of the enclosing functions and lambdas from the original column name. So `t.value + value` and `value + value` in the body of `value -> ...` were both named `plus(value, value)`, and `ActionsScopeNode::addFunctionIfNecessary` reused one for the other, which gave wrong results in `PREWHERE` and in `INTERPOLATE`. Now `ActionNodeNameHelper` asks `PlannerActionsVisitorImpl` for the name of such a column, so a derived name keeps the identity of its sources. The name of a column depends on the lambdas it is used in, and a query tree node can be shared, so when the expression has a shadowed column the names that depend on it are cached only for the use outside of lambdas. Expressions without such columns are named and cached as before.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=21 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…ments
Only the `ActionNodeNameHelper` inside `PlannerActionsVisitorImpl` knew how a column shadowed by a
lambda argument is named, and the name depended on the state of the visitor. The standalone
`calculateActionNodeName`, which names the arguments of aggregate and window functions and the sort
keys, calculated another name for the same expression, so e.g.
SELECT sum(arrayMap(`__table1.value` -> t.value + `__table1.value`, [toUInt8(1)])[1]) FROM t
could not find the argument of `sum` in the actions before aggregation.
The policy is now in `ActionNodeNameHelper` itself and depends only on the node and on the lambdas
that enclose it: inside the body of a lambda, a column that has the name of an argument of an
enclosing lambda is named `__shadowed_<n>.<name>`, and a column whose own name has this form is
escaped the same way, so the names of different columns never coincide. Both the visitor and the
standalone calculator use it.
The outermost scope of the actions, which has no lambda arguments, keeps the names that columns and
functions have outside of lambdas: a function of a lambda body that does not depend on lambda
arguments is added there under that name, and lambda scopes refer to it by the name it has in
lambdas. So the exported names do not change, and a `GROUP BY` key in the body of a lambda is found
among the inputs by its usual name. Aggregate and window functions are named as outside of lambdas,
as they are inputs of the actions.
Also mark `containsNode` as `[[nodiscard]]`, which failed the `arm_tidy` build:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121230&sha=3282688b34f6b18e0e26c7b46a3d89c7115425a5&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29
#121230
Co-Authored-By: Claude Fable 5.2 <[email protected]>
| return visitCorrelatedColumn(column_node_ptr); | ||
|
|
||
| auto column_node_name = action_node_name_helper.calculateActionNodeName(node); | ||
| auto column_node_name = action_node_name_helper.calculateColumnNodeName(node); |
There was a problem hiding this comment.
[Blocker] Disambiguate constant ALIAS columns before taking the early return
visitColumn still returns through visitConstant(expression, column_node_name) before reaching calculateColumnNodeNameInLambdas for a constant-backed ALIAS column. visitConstant registers that original name in every lambda scope, so it can still create or reuse the lambda argument's node. For example:
CREATE TABLE t (id UInt8, value UInt64 ALIAS 10)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (id) VALUES (0);
SELECT arrayMap(`__table1.value` -> t.value + `__table1.value`,
[toUInt8(1)]) FROM t;The expected result is [11]. Tracing the current code, the table column takes the constant shortcut under __table1.value; the lambda argument then reuses that same node, so both operands refer to the constant instead of distinct sources. The helper naming the enclosing expression uses __shadowed_0.__table1.value, but the builder never registers the constant under that name.
Please preserve the constant's outside name at the root and register it under its disambiguated name in lambda scopes too. Add regression cases for both operand orders. This is a source trace; no runnable ClickHouse binary is available in this review job.
| */ | ||
| bool is_input_node = function_node.isAggregationCall() || function_node.isWindowCall() | ||
| || actions_stack.front().containsInputOrConstantNode(function_node_name); | ||
| || actions_stack.front().containsInputOrConstantNode(outer_function_node_name); |
There was a problem hiding this comment.
[Blocker] Check lambda dependencies before reusing a grouped expression
A matching outside name does not establish that this function is the grouped expression: a lambda argument can have the same spelling as the table column's identifier. The shortcut runs before visiting the arguments and returns Levels(0), so it substitutes the table's group key for a function of the lambda argument:
CREATE TABLE t (value UInt64) ENGINE = Memory;
INSERT INTO t VALUES (10), (20);
SELECT arrayMap(`__table1.value` -> `__table1.value` + 1,
[count()])[1] AS k
FROM t
GROUP BY t.value + 1
ORDER BY k
SETTINGS optimize_injective_functions_in_group_by = 0;Each group has count() = 1, so both output rows must be 2. In the current source, the group key and the lambda body are both named plus(__table1.value, 1_UInt8). This branch consequently captures the group key (11 or 21) and never visits the lambda argument. Escaping table columns inside lambdas does not prevent this lookup against the unescaped root inputs.
Please make reuse of a grouped expression account for resolved column sources, or establish that the expression is independent of lambda arguments before taking this shortcut, and cover this case alongside the existing grouped-key capture test. This is a source trace; no runnable ClickHouse binary is available in this review job.
An outer column whose name collides with a lambda argument reached the lambda body with the wrong type,
and executing the body threw a logical error. Only the operand order decides it, because the planner
creates lambda arguments lazily, on the first reference to the name:
PlannerActionsVisitorImpl::visitColumnregistered every column it visits as anINPUTat every level ofthe actions stack, including a lambda scope that declares an argument of the same name. Inside a lambda
body such an
INPUTis the argument — that is how the capture loop ofvisitLambdatells argumentsapart from captured columns — so when the outer column was visited first it created the argument and gave
it the outer column's type. The body was then built for a type the argument does not have.
PREWHEREreaches this path because it does not use column identifiers as action node names, so the tablecolumn keeps the bare name
value. The synthetic column of anINTERPOLATEexpression has no columnidentifier at all and takes the same path, which is how the server AST fuzzer hit it on
master:Now a column whose name collides with an argument of the lambda scope is registered only under the
disambiguated name that the collision path already builds for it.
Also, a correlated column of the outer query in
PREWHEREwas not handled correctly.CollectPrewhereTableExpressionVisitorbound
PREWHEREto the table of the first column it met, also when that column was a correlated one, so the subquery'sPREWHEREfiltered the outer table and gave wrong results. A correlated column captured by a lambda escaped this check,and together with a column of the subquery's table threw
Trying to execute PLACEHOLDER action(found by the AST fuzzeron this PR's test).
PREWHEREcannot execute a correlated column at all, so it is now rejected withILLEGAL_PREWHERE(use
WHEREinstead), whether or not it is inside a lambda.The names of the functions and lambdas that use such a column are built from its disambiguated name as well.
Otherwise
t.value + valueandvalue + valuein the body ofvalue -> ...were both namedplus(value, value)and one action was silently reused for the other, which gave wrong results.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=710b4aa8c2e3560c254be50321f6c3be0a1be7df&name_0=MasterCI&name_1=Stress%20test%20%28arm_release%29
Regression check: the 1325 stateless tests that mention a lambda,
PREWHERE,INTERPOLATEorWITH FILLwere run against this branch, and every one of the 133 failures was then re-run against the unpatched
masterbuild from CI (710b4aa, 103 commits behind this branch's base). All 133 fail there too — they arelocal-environment gaps (
test.hits, distributed clusters, dictionaries, thetest_function.xmlUDF), notregressions.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
LOGICAL_ERRORUnexpected return typewhen a lambda body references an outer column that has the same name as one of the lambda's own arguments, for example a table column inPREWHEREor the interpolated column ofORDER BY ... WITH FILL ... INTERPOLATE. A correlated column of the outer query inPREWHEREof a subquery, which could give wrong results, is now rejected withILLEGAL_PREWHERE.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121230]