Skip to content

Fix Unexpected return type when a lambda argument shadows an outer column - #121230

Open
alexey-milovidov wants to merge 32 commits into
masterfrom
fix-interpolate-column-in-lambda-body
Open

alexey-milovidov wants to merge 32 commits into
masterfrom
fix-interpolate-column-in-lambda-body

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

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:

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.'

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 — 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.

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.

Also, a correlated column of the outer query in PREWHERE was not handled correctly. CollectPrewhereTableExpressionVisitor
bound PREWHERE to the table of the first column it met, also when that column was a correlated one, so the subquery's
PREWHERE filtered 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 fuzzer
on this PR's test). PREWHERE cannot execute a correlated column at all, so it is now rejected with ILLEGAL_PREWHERE
(use WHERE instead), 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 + value and value + value in the body of value -> ... were both named plus(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, INTERPOLATE or WITH FILL
were run against this branch, and every one of the 133 failures was then re-run against the unpatched
master build from CI (710b4aa, 103 commits behind this branch's base). All 133 fail there too — they are
local-environment gaps (test.hits, distributed clusters, dictionaries, the test_function.xml UDF), not
regressions.

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):

Fix LOGICAL_ERROR Unexpected return type when 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 in PREWHERE or the interpolated column of ORDER BY ... WITH FILL ... INTERPOLATE. A correlated column of the outer query in PREWHERE of a subquery, which could give wrong results, is now rejected with ILLEGAL_PREWHERE.

🤖 Generated with Claude Code


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

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e9e0b6e]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

AI Review

Summary

The PR separates shadowed outer columns from lambda arguments, shares action naming with its consumers, and rejects correlated columns in PREWHERE. The previous inline findings are addressed in the current code, but two remaining shortcuts can still substitute the wrong source and produce incorrect results.

Missing context / blind spots
  • ⚠️ Findings below are source traces at e9e0b6e5be0930845c6dedb1369d28cd3ca2ac61, not executed reproductions. This job has no ClickHouse binary. The current Praktika report has a failed build and skipped functional jobs; run the focused cases below to close the runtime validation gap.
Findings

❌ Blockers

  1. src/Planner/PlannerActionsVisitor.cpp:1004: Constant ALIAS columns bypass disambiguation. The early return at line 1012 sends the original column name to visitConstant, which registers it in every lambda scope. For value UInt64 ALIAS 10, arrayMap(`__table1.value` -> t.value + `__table1.value`, [toUInt8(1)]) can reuse the constant as the argument instead of producing [11]. Preserve the root name while registering the disambiguated name in lambda scopes, including this constant path.
  2. src/Planner/PlannerActionsVisitor.cpp:1447: Group-key reuse ignores lambda dependencies. With table values 10 and 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 should return 2 twice. The body and root group key share plus(__table1.value, 1_UInt8), so the shortcut captures the group key and returns Levels(0) without visiting the argument. Check resolved source identity or lambda independence before reusing a root input.

💡 Nits

  • The dedicated arm_tidy build already reports missing [[nodiscard]] on calculateColumnNodeName and calculateColumnNodeNameInLambdas. No inline finding was posted for these CI-reported diagnostics.
Tests
  • ⚠️ Add a stateless case for a constant ALIAS column shadowed by a quoted identifier, in both operand orders; assert [11].
  • ⚠️ Add the inverse of the existing grouped-key capture case: the lambda computes from its own argument while a same-spelled table expression is a group key. Assert 2 for both groups in the example above.
Final Verdict

Status: ❌ Block

Preserve source identity through constant-column registration and grouped-expression reuse, and add the two focused regression cases.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 20, 2026
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 20, 2026
alexey-milovidov and others added 2 commits September 25, 2026 19:21
…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]>
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c6f6841a4 with master 58726cc5c (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

5 object files changed (+31.98 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/PlannerActionsVisitor.cpp.o 692.34 KiB 720.97 KiB +28.63 KiB (+4.14%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.58, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 10.7 s +7.0 s (+188%)
Compile time of recompiled translation units

9 translation units recompiled, 33 s compile time in total, 9 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits October 3, 2026 01:28
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The remaining red jobs (AST fuzzer (amd_debug, targeted), AST fuzzer (amd_debug, targeted, old_compatibility), Stress test (arm_tsan)) all fail with Logical error: Trying to execute PLACEHOLDER action (STID 1611-3e1e / 1611-4266). This is a pre-existing issue: a correlated subquery whose PREWHERE references a column of the outer query. It also occurs on master (Stress test (amd_debug), 2026-09-12) and in other PRs. The fuzzer reached it by mutating the EXPLAIN queries of this test. The fix is in progress in #122397.

This push also merges master and addresses the review thread about nested lambdas.

Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (17c6b20) and fixed the Fast test failure in 04647_matcher_in_lambda_join_use_nulls (132b5c0).

The failing query was SELECT a, v, w FROM p1 FULL JOIN p2 USING (a) PREWHERE arrayMap(z -> tuple(* EXCEPT w), [1])[1].1 = 9. PREWHERE is resolved with allow_resolve_from_using disabled, so an identifier there names the left table's column. But a matcher inside a lambda runs in the lambda's own scope, so it still expanded the USING key to firstNonDefault(__table1.a, __table2.a). Now that this PR checks lambda bodies in PREWHERE, the column from the right table was rejected with ILLEGAL_PREWHERE. On master, the planner quietly read __table2.a as the left table's column with the same name. For example, PREWHERE arrayMap(z -> p2.a, [1])[1] = 0 filters on p1.a there.

The fix takes the USING column from the left table when a matcher is in PREWHERE, the same way an identifier is resolved. The results of 04647_matcher_in_lambda_join_use_nulls stay the same, and I checked them against a master binary. A matcher that really reaches a column of the other table now gets a clear ILLEGAL_PREWHERE; on master it failed with NOT_FOUND_COLUMN_IN_BLOCK. I added these cases to 05233_lambda_argument_shadowed_column_visit_order. Locally, 04647, 05233 and 04058 pass, with and without randomized settings.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits October 23, 2026 19:16
…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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 hasToken(lc, 'v299'), looks like #106922) and provide a fix in a separate PR. If the fix is already in progress, link it here. The other failure, the hung 04117_detach_database_kill_query query in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel), is handled by #127149.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the pre-existing Nullable text-index bug from #106922, not related to this PR. The fix in progress is #113332, so I am not opening a separate PR.

In this run tab__fuzz_1.lc is still LowCardinality(Nullable(String)) (3001 rows, 61 NULL). Direct read replaces hasToken(lc, 'v299') with the UInt8 text-index virtual column, which holds 0 for a NULL row, so the not arm keeps the 61 rows the isNull arm also counts: 10 + 2991 + 61 = 3062 against 3001.

It reproduces on master 8e3eb7a without the fuzzer:

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 NULLs at the replacement site, and its test covers NOT hasToken on LowCardinality(Nullable). It currently has a merge conflict with master (last push 2026-09-03).

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits October 26, 2026 13:33
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (d131adb) with no conflicts. CI on the previous commit was fully green, and there are no unresolved review threads. 05233_lambda_argument_shadowed_column_visit_order and 04058_constraint_subst_correlated_subquery_crash both pass locally on the merged tree.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (1341690) with no conflicts to pull in dd4ac12b1ec4, which fixes the flaky test_read_temporary_tables_on_failure/test.py::test_different_versions (the only failure on the previous commit, in the targeted integration jobs; it relied on a client timeout to keep the query slot occupied and is unrelated to this PR). The affected translation units build; there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (c6f6841) with no conflicts, since the branch was more than a week behind. CI on the previous commit was green, and there are no unresolved review threads. 05233_lambda_argument_shadowed_column_visit_order, 04058_constraint_subst_correlated_subquery_crash and 04647_matcher_in_lambda_join_use_nulls pass locally on the merged tree.

Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
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.
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
@stresshouse

stresshouse Bot commented Nov 21, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

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
  • StressHouse run: a45a608b-e787-438f-ab01-9ab88100c0e9
  • MIRAI run: 27d5a960-d47d-4912-91f4-c68570659c17
  • PR check IDs:
    • clickbench_590697_1795230054
    • clickbench_590703_1795230054
    • tpch_adapted_1_official_590710_1795230054
    • tpch_adapted_1_official_590730_1795230054

alexey-milovidov and others added 2 commits November 24, 2026 03:45
…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);

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.

[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);

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.

[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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants