Skip to content

Check PREWHERE column support inside lambda bodies - #114721

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:prewhere-lambda-body-column-check
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:prewhere-lambda-body-column-check

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #114206

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

Fixes a logical error and a NOT_FOUND_COLUMN_IN_BLOCK error when a PREWHERE expression reads a table column inside a lambda body, e.g. PREWHERE arrayMap(x -> t.c, [1])[1] > 0. Such a column was never checked against the table expression's supported PREWHERE columns, so a Merge whose children declare it with different types built the filter against the wrong one rather than refusing it. Also fixes UNKNOWN_FUNCTION for a PREWHERE expression calling an executable or WebAssembly UDF that does not itself read a JOIN column.

Description

CollectPrewhereTableExpressionVisitor::needChildVisit skipped LAMBDA, so a column read only inside a lambda body never reached visitImpl, the one place that picks the table expression PREWHERE reads from and enforces supportedPrewhereColumns. On master:

  • A Merge whose children declare x as UInt32 and Nullable(UInt32) excludes x from its contract, but the guard that would refuse it never runs. The filter is built against the root's type while a child reads another, so the lambda's ColumnFunction capture fails in the reader: Cannot capture column N ... incompatible type, a logical error, so an abort under sanitizers.
  • With no column visited, PREWHERE is pinned to the first table expression, so a lambda over another fails Code: 10 (Code 10 NOT_FOUND_COLUMN_IN_BLOCK for a right-side join column inside a lambda in PREWHERE #114206).

The fix descends into lambda bodies, skipping only the lambda's own parameters by testing for a LAMBDA_ARGS column source, as the sibling CollectSourceColumnsVisitor already does: a node type, not a function name, so all higher-order functions are covered.

Collecting those columns makes two latent omissions live. ReplaceColumnsVisitor never entered a lambda either, so the JOIN type substitution that PREWHERE must roll back survived inside a lambda and aborted at join_use_nulls = 1. Rolling it back also re-derives the lambda's parameter types from the array its higher-order function iterates.

It also rebuilt every function in the expression, replaced or not, through FunctionFactory, which does not own UDFs: hence the UNKNOWN_FUNCTION. It is now bounded to replaced subtrees, so a UDF reading a restored JOIN column stays refused as on master.

Reported by @ nikitamikhaylov on #113768: one Server died in that PR's unrelated Stress test (amd_msan), report.

Validation

Reproducer (aborts on master, ILLEGAL_PREWHERE with this change):

CREATE TABLE t  (x UInt32)           ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE t2 (x Nullable(UInt32)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (100);
INSERT INTO t2 VALUES (300);
SET enable_analyzer = 1;
SELECT x FROM merge(currentDatabase(), '^t') AS m
PREWHERE (arrayMap(x -> m.x, [1])[1]) > 50;

04879_prewhere_lambda_body_column_check: 29 arms A/B'd against a base build, 8 refusals and
21 row-returning. Every refusal and every join_use_nulls shape is paired with the same query
without a lambda, so each expected outcome is justified against master's own answer.

arm base with this change
diverging child types, lambda reads m.x (also *, arrayFilter) abort ILLEGAL_PREWHERE
ARRAY JOINed alias inside a lambda Code: 10 ILLEGAL_PREWHERE
lambda over the second table of a JOIN Code: 10 resolves to that table
LEFT JOIN, right column in arrayExists, join_use_nulls 0 and 1 (#114206) abort or Code: 10 1 / 2
the same four without a lambda as after the change unchanged
agreeing types; WHERE; unrestricted table; shadowed parameter rows unchanged

04889_prewhere_lambda_executable_udf covers the UDF case in 9 arms, with a built-in control.

Five mutation arms, disjoint casualties: reverting needChildVisit re-introduces the abort and
the Code: 10; dropping the LAMBDA_ARGS guard breaks 04108; reverting
ReplaceColumnsVisitor aborts in ActionsDAG; dropping either return-type refresh or the
parameter-type re-derivation aborts in planning or in ColumnFunction::appendArgument.

04108, 03036_prewhere_lambda_function, 00729_prewhere_array_join and
02955_analyzer_using_functional_args pass unchanged. Both new tests ran 50x, 0 failures:
04879 under randomized settings, 04889 at clickhouse-local defaults.

CollectPrewhereTableExpressionVisitor::needChildVisit returned false for
LAMBDA, which discarded the whole lambda body along with the lambda's
parameters. A table column referenced only inside the body therefore never
reached visitImpl, the single place that picks the table expression PREWHERE
reads from and enforces IStorage::supportedPrewhereColumns().

That skip was introduced to stop lambda parameters being treated as table
columns, but it was at the wrong granularity. Two consequences, both
reachable from plain SQL with the analyzer enabled:

- A Merge table whose children declare a column with different types has it
  correctly erased from the PREWHERE contract, yet the guard that would
  reject the query is never reached. The filter is built against the root's
  type while a child reads another, and the lambda's ColumnFunction capture
  fails inside the reader with "Cannot capture column N because it has
  incompatible type". Being a logical error, that aborts the server in debug
  and sanitizer builds and raises the wrong exception in a release build.
  Spelled without a lambda, the same query is already refused with
  ILLEGAL_PREWHERE, so the lambda form bypassed an existing refusal.
- With no column visited, getPrewhereTableExpression() returns null and
  PREWHERE falls back to the first table expression, so a lambda over any
  other one fails with NOT_FOUND_COLUMN_IN_BLOCK (issue ClickHouse#114206).

Descend into lambda bodies and skip only the lambda's own parameters, by
testing for a LAMBDA_ARGS column source. The sibling
CollectSourceColumnsVisitor in this file already performs that exact test,
so the two visitors are now consistent, and no interface, method or setting
is added. The gate is a node type rather than a function name, so every
higher-order function is covered.

Collecting such a column also makes it reach execution, so the restoration
that keeps a PREWHERE expression's type stable across a JOIN has to reach it
too. QueryAnalyzer runs ReplaceColumnsVisitor over PREWHERE to undo the
join_use_nulls substitution, and that visitor did not enter a LAMBDA either,
so with join_use_nulls = 1 the predicate kept a Nullable type the storage
header does not have. Let it descend as well, and refresh the lambda's
cached body return type after a replacement, since it is derived from the
body and is asserted against the actions DAG during planning. A lambda
parameter cannot be substituted here: every key of the replacement map is a
join or USING column, and query tree node equality compares a column's
source, which for a parameter is the lambda's own argument list.

This changes behaviour intentionally: a lambda in PREWHERE over a storage
whose contract excludes that column now throws ILLEGAL_PREWHERE. Such a
query was never sound, because a filter pushed into the child read has no
correct input for an excluded column. For the same reason, an ARRAY JOINed
alias referenced inside a PREWHERE lambda now throws ILLEGAL_PREWHERE
instead of NOT_FOUND_COLUMN_IN_BLOCK from deeper in execution, matching
what the spelling without a lambda already did.

Reported by nikitamikhaylov on ClickHouse#113768, where it surfaced as one "Server
died" in Stress test (amd_msan) unrelated to that pull request.

Related: ClickHouse#114206
A lambda's parameter types are not its own: each is derived from the array
argument the enclosing higher-order function iterates. PREWHERE undoes the
JOIN type substitution on the columns it reads, so restoring a column inside
such an array leaves the lambda's cached parameter types describing the
pre-restoration type.

Nothing downstream re-derived them. rerunFunctionResolve rebuilds a function
from its argument columns but never calls getLambdaArgumentTypes, and
FunctionArrayMapped::getReturnTypeImpl deliberately skips the check because
getLambdaArgumentTypes is expected to have done it. The planner then read the
stale cache into FunctionCaptureOverloadResolver, and the capture failed the
type check in ColumnFunction::appendArgument.

Re-derive the parameter types through the function's own resolver, so the
tuple-unpacking and LowCardinality handling each higher-order function
applies is preserved, and re-type the body columns that read them.

Reachable only once the column is collected for PREWHERE, which the
CollectTableExpressionData change in this PR enables.
…ed parameter

When PREWHERE restores a JOIN-substituted column that sits in the OUTER
higher-order function's array argument, the outer lambda's parameter types are
re-derived and its body columns are retyped. An inner lambda that captures the
outer parameter therefore changes body result type - but its own array argument
is unchanged, so rerunLambdaArgumentsResolve finds
derived_argument_types == lambda_node.getArguments().getTypes() and takes the
early continue that skips the lambda_node.resolve() refreshing the return half.
No other writer of LambdaNode::result_type runs afterwards, so
PlannerActionsVisitor::visitLambda builds FunctionCaptureOverloadResolver from
the live body type and then compares it against the stale cache, which is a
LOGICAL_ERROR - a server abort in debug and sanitizer builds.

RetypeLambdaArgumentColumnsVisitor::visitImpl only handled ColumnNode and
FunctionNode, and its bottom-up traversal meant nothing repaired the miss later.
Add a LambdaNode branch that rebuilds the cached DataTypeFunction from the
lambda's existing argument types plus its current body type, mirroring the
equivalent branch in ReplaceColumnsVisitor. Argument types are taken verbatim:
re-deriving them belongs to the enclosing higher-order function. needChildVisit
already admits LAMBDA, so nested lambdas at any depth are reached.

This is the same defect class as the parameter-type re-derivation one level of
nesting out, and it needs its own repair: the existing arms all put the restored
column in the inner array, which changes the inner parameter and so never
reaches the early continue.

The shape aborted on the pre-fix tree with 'Cannot capture column 4 because it
has incompatible type', so the query was already reaching a LOGICAL_ERROR rather
than merely being refused.

Five arms added to 04879: the capture shape at join_use_nulls 1 and 0, the same
capture two lambdas down, and two non-JOIN controls where nothing is restored.
Each expected output is justified against the base binary and equals the
non-lambda spelling's rows.
…laced

The PREWHERE column restoration visited every resolved function under the
expression and rebuilt each one, whether or not a replacement had happened
beneath it. Rebuilding goes through FunctionFactory, which does not own every
function the analyzer can resolve: an executable UDF is resolved through
UserDefinedExecutableFunctionFactory and a WebAssembly UDF through
UserDefinedWebAssemblyFunctionFactory, and both are recorded as ordinary
functions. Rebuilding one therefore failed with UNKNOWN_FUNCTION, refusing a
query that had nothing to do with the restoration.

Admitting lambda bodies into the traversal made this reachable for a UDF inside
a lambda, where it had previously been unreachable. It is now bounded by the
invariant that was missing: re-resolve a node only when a replacement occurred
at it or below it, so a node whose types nothing invalidated is left alone.

The same unconditional rebuild existed in the lambda body retyping added
earlier in this pull request, and is bounded the same way. Both are tracked per
subtree rather than per visitor, because a restored join column elsewhere in the
same PREWHERE must not drag an untouched sibling into a rebuild.
A higher-order function derives its lambda's parameter types from its array
arguments, so restoring one of those columns can change some parameters and
leave the rest alone. Re-type only the ones that changed, so a read of an
untouched sibling parameter is not rebuilt through a factory that may not own
its function: an executable UDF over an unchanged parameter of a
multi-parameter lambda was refused UNKNOWN_FUNCTION when another parameter
came from a restored JOIN column.
The lambda-cache comment carried defect history, and the replaced_subtrees
comment claimed an ownership guarantee that does not hold: replacing a node
releases the old subtree whose children were already recorded. The addresses
are only ever tested for membership, which is what the comment now says.
@groeneai

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

Reviewed cold against the resulting code, then re-reviewed by an independent model (engine: codex)
and adjudicated against the recorded validation evidence. 6 review rounds, 1 replan round. The
round-6 fix round was the last one, so the tree is published as it stands and the two residuals
below are disclosed rather than fixed.

# Sev Finding Verdict
1 ❌ CollectPrewhereTableExpressionVisitor was fixed but ReplaceColumnsVisitor still skipped LAMBDA, so the JOIN type substitution PREWHERE rolls back survived inside a lambda body and aborted at join_use_nulls = 1. AGREE, fixed
2 ❌ A nested lambda's parameter types are derived from the array it iterates, so restoring a column inside that array left them stale. AGREE, fixed
3 ❌ An inner lambda that only captures an outer parameter keeps its own parameter types, so re-resolving its higher-order function left its cached return type stale. AGREE, fixed
4 ❌ Re-resolving rebuilt every function in the expression through FunctionFactory, which does not own executable or WebAssembly UDFs, so a PREWHERE calling one was refused with UNKNOWN_FUNCTION. AGREE, fixed
5 ❌ That rebuild still reached a UDF reading an unchanged parameter of a multi-parameter lambda when another parameter came from a restored column. Retyping is now per parameter. AGREE, fixed
6 ⚠️ A validation claim of a randomized 300/300 was not what was measured: the one genuinely randomized run finished 41/50, and all 9 failures were CLUSTER_DOESNT_EXIST 'parallel_replicas' from the local server not loading clusters.xml. The claim was the defect, not the test. AGREE, corrected to the measured methodology
7 💡 Six countable claims in the validation text were stale or overstated across rounds (arm, refusal, control and mutation counts; the UDF test's arm count; and randomization attributed to a test that runs at clickhouse-local defaults). AGREE, each re-measured and corrected
8 💡 Two source comments narrated the defect history rather than the standing invariant, and one asserted a pointer-ownership guarantee that does not hold. AGREE, rewritten as invariants
9 💡 The CI report and PR URLs are absent from the commit messages. DISAGREE: the standing directive asks for the issue link and the full canonical report URL in the PR description, which this body carries (a Related: line plus the json.html?PR=...&sha=...&name_0=...&name_1=... form). No rule places them in commit messages, and the line cited for it says something else.

Noted, not blocking:

  • Admitting LAMBDA into ReplaceColumnsVisitor costs one getTreeHash per lambda node even when
    the replacement map is empty, because the map key's converting constructor hashes the whole
    subtree before find is entered. IQueryTreeNode::getTreeHash documents this pattern and its
    remedy: skip the lookup when the container is empty, as QueryAnalyzer and
    PlannerActionsVisitor already do for their own maps. Latency only, no behaviour change, and it
    needs hundreds of nested lambdas in one PREWHERE to matter; the timings offered for it were not
    self-consistent. Worth a follow-up guard.
  • 04889's preamble says nothing is replaced in any of its expressions. That holds for the UDF
    subtree, which is what the test asserts, but several arms deliberately place a restored JOIN
    column beside it. Comment wording only.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260813-203800

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [39164d6]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Unexpected return type from A. Expected B. Got C (STID: 2458-5396) FAIL cidb

AI Review

Summary

This PR fixes several real lambda-related PREWHERE gaps in the analyzer and the implementation looks internally consistent, but the Bug Fix contract is still not proven by the added regression tests. CI's Finish Workflow hook rejected the PR because none of the per-arch Bugfix validation jobs established a fail-on-master / pass-on-patch transition for the new functional tests.

Tests
  • ⚠️ [tests/queries/0_stateless/04879_prewhere_lambda_body_column_check.sql:23] The new stateless coverage is still missing the evidence ClickHouse requires for a Bug Fix: at least one per-arch Bugfix validation job must succeed strictly (OK/XFAIL). In this run every per-arch validator was DROPPED, so the regression either does not reproduce on master HEAD anymore or the reproducer is not expressed in a way the validator can confirm. Please tighten the minimal failing arm until one validator proves the before/after difference.
Final Verdict

⚠️ Changes requested: the fix needs a bugfix-validating regression test before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 102/123 (82.93%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Seven lines of SQL through clickhouse local, rc=134 on every run of each aborting arm, and rc=46 UNKNOWN_FUNCTION on every run of each executable-UDF arm. No probabilistic arm anywhere.
b Root cause explained? Yes. CollectPrewhereTableExpressionVisitor::needChildVisit returned false for LAMBDA, discarding the lambda body along with its parameters, so a column referenced only in the body never reached visitImpl (CollectTableExpressionData.cpp:280-339), the only place that picks the PREWHERE table expression and enforces supportedPrewhereColumns(). StorageMerge correctly erases the diverging column, the guard is never reached, the filter is built on the root's type and the ColumnFunction capture fails at ColumnFunction.cpp:426 under MergeTreeRangeReader.cpp:1005. Collecting the column then exposed a second, symmetric gap on the restoration side: PREWHERE undoes the JOIN type substitution, but a lambda's parameter types are derived from the array argument its higher-order function iterates, and nothing re-derived them - rerunFunctionResolve (Utils.cpp:942) never calls getLambdaArgumentTypes, and FunctionArrayMapped::getReturnTypeImpl (FunctionArrayMapped.h:227) skips the check on the stated grounds that getLambdaArgumentTypes already did it. The planner read the stale cache into FunctionCaptureOverloadResolver (PlannerActionsVisitor.cpp:1055) and the capture failed the same type check.
c Fix matches root cause? Yes. The refusal is restored at the layer owning the contract, not guarded at the failure site (ColumnFunction::appendArgument) nor in MergeTreeRangeReader. A reader-side guard would mask an unsound plan and leave the NOT_FOUND_COLUMN_IN_BLOCK shape broken.
c2 Every behaviour change enumerated? Yes, three, all measured and tested: the Merge diverging-type abort becomes ILLEGAL_PREWHERE; the right-side join column in a lambda stops failing with NOT_FOUND_COLUMN_IN_BLOCK and returns the same rows as its non-lambda spelling; and an ARRAY JOINed alias in a PREWHERE lambda now throws ILLEGAL_PREWHERE rather than NOT_FOUND_COLUMN_IN_BLOCK from deeper in execution, matching what the spelling without a lambda already did. The third is named in the commit message.
d Test intent preserved / new tests added? Yes. New 04879_prewhere_lambda_body_column_check: 29 labeled arms, 8 of them expected refusals (serverError) - the 2 aborting Merge shapes, an ARRAY JOIN lambda/non-lambda pair, issue #114206's own LEFT JOIN + arrayExists query with its two agreeing oracle spellings, the join_use_nulls arms, nested-lambda arms at depth 2 and 3 in the arrayExists/arrayMap/arrayFilter spellings, a two-table lambda body refused alongside its non-lambda control, and the controls. 04108_lambda_column_name_collision_bug, 03036_prewhere_lambda_function, 00729_prewhere_array_join and 02955_analyzer_using_functional_args are untouched and pass; 04108 is demonstrably the oracle for one mutation arm. New 04889_prewhere_lambda_executable_udf: 7 arms over the existing scripts_udf executable UDF, covering it outside a lambda, inside one, nested, beside a restored join column in both argument orders, and inside a lambda whose own parameter is the restored column.
e Both directions demonstrated? Yes. Per-arm base-vs-fix table with Build IDs recorded for both binaries: aborting arms rc=134 -> rc=182 ILLEGAL_PREWHERE, #114206's query rc=10 NOT_FOUND_COLUMN_IN_BLOCK -> correct rows, the ARRAY JOIN lambda rc=10 -> rc=182, controls byte-identical. Every expected-error annotation is justified against the base binary, so no arm pins a newly-introduced refusal as if it were pre-existing. Independently, the new test kills a base server (Reason: server died) and passes on the patched one. The executable-UDF arms are likewise three-way where they can be: the lambda spellings return rows on base, UNKNOWN_FUNCTION before the re-resolve was bounded, and rows again with it; the non-lambda spellings already threw on base and now return rows. The nested-capture arms are three-way: they abort on base (Cannot capture column 4 ...), abort differently before the nested-lambda refresh (Lambda resolved type ... is not equal to type from actions DAG), and return the non-lambda control's rows with it. The multi-parameter arm is four-way: it aborts on base, is refused UNKNOWN_FUNCTION before the per-parameter bound, is refused again by a mutation that neutralises that bound, and returns rows with it, with a builtin control at the same arity that agrees with base on the abort and diverges only where the UDF does.
f Fix is general across code paths? Yes. Every needChildVisit in src/ was enumerated; after the fix exactly one still names LAMBDA in its admitted set (ReplaceColumnsVisitor.h, admitting it deliberately), and no other visitor carries the blanket skip. The sibling CollectSourceColumnsVisitor in the same file already had the correct LAMBDA_ARGS guard, so the two are now consistent. Both visitors that re-resolve a restored PREWHERE expression are bounded the same way (ReplaceColumnsVisitor, RetypeLambdaArgumentColumnsVisitor): each re-resolves a node only when a replacement happened at it or below it, so a function nothing invalidated is never rebuilt through FunctionFactory, which does not own executable or WebAssembly UDFs. Inside the parameter-retyping visitor the same rule is applied one level finer, per lambda parameter: a read of a parameter whose derived type did not change is not marked, so an untouched sibling read is not rebuilt either. The sibling ReplaceColumnsVisitor needs no per-parameter equivalent because it tracks node identity rather than parameter indexes. The remaining rerunFunctionResolve callers only visit nodes they have just mutated, so they cannot reach this. All 12 classes overriding supportedPrewhereColumns() (StorageMerge, StorageBuffer, StorageFile, StorageObjectStorage, StorageMaterializedView, StorageProxy, StorageTableFunctionProxy, StorageAlias, StorageDummy, IStorageURLBase, StorageURLDatabaseTable, StorageURLSchemeDispatch) reach the same guard and become enforced for lambda bodies, intentionally, since all were already enforced for the non-lambda spelling. (MergeTreeData and StorageMaterializedPostgreSQL override only the supportedPrewhereColumnsIncludeSubcolumns sibling, so they are not in this set.)
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The gate is a node type, not a function name, so every higher-order function is covered by construction; the test pins that with arrayFilter and arrayExists arms next to arrayMap, at nesting depth 1, 2 and 3, and with the outer parameter captured by an inner lambda at depth 2 and 3. The parameter-type re-derivation delegates to each function's own getLambdaArgumentTypes, so the tuple-unpacking and LowCardinality cases are handled by the same authority function resolution uses, and arrayFold's accumulator arity is honoured rather than assumed. The diverging pair under test is UInt32 vs Nullable(UInt32), plus UInt64 vs Nullable(UInt64) for the join arms at join_use_nulls 0 and 1; the same-type, unrestricted-storage and non-JOIN arms pin the negative side; 04108 covers nested, shadowed, sibling and multi-column lambdas. Lambda arity is covered at one and two parameters, including the mixed case where only one of the two parameters is restored.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or re-defaulted, so no SettingsChangesHistory.cpp entry is needed, and no serialization or format change. There is one intended behaviour change, stated in the description: a lambda in PREWHERE over a storage whose contract excludes that column now throws ILLEGAL_PREWHERE instead of aborting or filtering on the wrong type. That query was never sound and the non-lambda spelling already threw, so this removes an inconsistency rather than restricting working behaviour.
i Invariants and contracts preserved? Yes. visitImpl's postcondition (a single table expression, all columns admitted by the contract) is strengthened, not weakened. The early return precedes every mutation, so table_expression, table_storage_snapshot and table_supported_prewhere_columns are never half-assigned on the lambda-parameter path. The restoration path now re-establishes the query tree's own type invariant rather than half of it: a lambda's parameter types, the body columns that read them, the functions built on those columns, and the lambda's result type are all re-resolved together, which is what QueryTreePassManager's post-pass validation checks. No locking, allocation, lifetime or error-path change; this is single-threaded planning-time code.
j Each half independently load-bearing? Yes, proven by four mutation builds, each dropping exactly one half: reverting the needChildVisit LAMBDA admission gives Unexpected return type from notEquals; dropping the lambda result-type refresh gives Lambda resolved type ... is not equal to type from actions DAG; dropping the parameter-type re-derivation gives Cannot capture column 2 ... got UInt64, but Nullable(UInt64) is expected on the nested arm while the non-nested arm still passes, so the third half is not redundant with the second; and dropping the nested-lambda return-type refresh reddens only the outer-capture arm while every other lambda arm still passes, so the fourth half is not redundant with the second either (it shares that half's abort site, PlannerActionsVisitor.cpp:1062, because both break the same cached field on different paths - the disjoint arm sets are the discriminator, not the message). Two further mutation builds cover the re-resolve bound, one per site: removing it in ReplaceColumnsVisitor reddens the first UDF arm, removing it in RetypeLambdaArgumentColumnsVisitor reddens only the arm whose lambda parameter is the restored column, so those two are not redundant with each other either.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @novikd, could you review this? The PREWHERE column collection skipped LAMBDA entirely, so a table column read only inside a lambda body never reached the check that picks the PREWHERE table expression and enforces supportedPrewhereColumns; descending into the body then required the JOIN type substitution to be rolled back there too, which re-derives a higher-order function's lambda parameter types via getLambdaArgumentTypes.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 14, 2026

SELECT 'unsupported column inside a lambda body, qualified';
SELECT x FROM merge(currentDatabase(), '^pw_lam_u32$|^pw_lam_nul$') AS m
PREWHERE (arrayMap(x -> m.x, [1])[1]) > 50 ORDER BY x; -- { serverError ILLEGAL_PREWHERE }

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.

Because this PR is labeled Bug Fix and adds new functional tests, we need at least one per-arch Bugfix validation job to prove a fail-on-master / pass-on-patch transition. Finish Workflow currently reports all four per-arch validators as DROPPED, so none of the new stateless tests actually validated the regression. Can you tighten the reproducer or split out the minimal failing arm until one validator goes OK/XFAIL?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The DROPPED status this is based on is not what the run reports. Counting leaves in the praktika report for this head (result_pr.json, 177 leaves) gives 0 dropped: 111 PENDING, 35 OK, 18 SKIPPED, 12 RUNNING, 1 FAIL.

The five Bugfix validation leaves are:

leaf status info
functional tests, amd64 PENDING
functional tests, aarch64 PENDING
unit tests PENDING
integration tests, amd64 SKIPPED Skipped, no integration tests updates
integration tests, aarch64 SKIPPED Skipped, no integration tests updates

Finish Workflow is itself still PENDING, so it has not reported on them. Config Workflow is success and the can be tested label is present, so this is not a config stall or a label gate either. The run is simply still in flight.

So no validator has judged the reproducer yet, and I am not going to re-cut the test to chase a status that has not been emitted. The fail-on-master / pass-on-patch transition is already measured locally: both aborting arms go from abort on master to ILLEGAL_PREWHERE with the patch, and 04879 carries per-half mutation arms that re-redden when either half of the fix is reverted.

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 39164d613 with master a55ac986a (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
Binary Master PR Δ
programs/clickhouse-stripped 692.04 MiB 689.04 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

7 object files changed (+47.31 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Utils.cpp.o 416.77 KiB 461.40 KiB +44.63 KiB (+10.71%)

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

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 39164d6

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.

CI is fully finished on this head: 177 leaves, 159 success / 17 skipped / 1 failure, 0 dropped jobs.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Unexpected return type from FunctionExpression (STID 2458-5396) pre-existing trunk logical error, surfaced here because this PR removes an earlier NOT_FOUND_COLUMN_IN_BLOCK refusal that masked it a fix task is created (investigating at full effort - fixing-PR link to follow here)

On the one failure: the fuzzer mutated this PR's own new fixture tables, so it looks PR-caused,
but it is not. I reproduced it on the official master release build (26.8.1.1384) and on a
pristine master debug snapshot, both of which provably lack this change, with a single-table
query that needs no join and no join_use_nulls:

CREATE TABLE t (v UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT 10 UNION ALL SELECT 20;
SELECT v FROM t PREWHERE arrayExists(v -> (t.v != 0) AND (v = 7), [toNullable(toUInt64(7))]) ORDER BY v;

Three conditions are each necessary, isolated by their own control: a lambda parameter whose name
collides with a table column, that column read in the lambda body, and a nullable lambda argument.
It is PREWHERE-only and operand-order dependent, so short-circuit driven. On master the fuzzer's
JOIN spelling is refused earlier with NOT_FOUND_COLUMN_IN_BLOCK, which is the bug this PR fixes;
with the fix the query proceeds into execution and meets this independent defect. No wrong results:
discriminating values give byte-identical rows for colliding and non-colliding parameter names, so
the consequence is confined to the logical error. It is out of scope for this PR (no join, no
lambda-body collection) and is tracked separately.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted, old_compatibility) failure in the ledger above, Unexpected return type from FunctionExpression (STID 2458-5396): #115005. The defect is pre-existing on master and independent of this PR; a lambda parameter named after a table column took the column type in PREWHERE.

@PedroTadim

Copy link
Copy Markdown
Member

This is not going to be supported

@PedroTadim PedroTadim closed this Aug 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, I will not reopen it.

One part of that PR was separable and I would rather ask than assume. Resolving a PREWHERE column that a lambda reads from another table expression is the support question, and your close plus KochetovNicolai's ruling on #114206 point the same way. The other part only ran the existing supportedPrewhereColumns check on columns that appear solely inside a lambda body. Without it that check never runs, so the query is not refused, it aborts in the reader. Still live on master 26.8.1.1553:

CREATE TABLE t  (x UInt32)           ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE t2 (x Nullable(UInt32)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (100);
INSERT INTO t2 VALUES (300);
SELECT x FROM merge(currentDatabase(), '^t') AS m PREWHERE (arrayMap(x -> m.x, [1])[1]) > 50;
-- Code: 49 Cannot capture column 2 ... got UInt32, but Nullable(UInt32) is expected. (LOGICAL_ERROR)

The same predicate without the lambda is refused: Code: 182 ... does not support column m.x in PREWHERE. No join is involved.

If you want that refusal, it is the needChildVisit change plus a LAMBDA_ARGS guard and nothing else, and I will open it that small. If you would rather leave it as it is, say so and I will close this out.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Another sighting of this hole, and this one changed severity class: a segmentation fault in a release
build, not the logical error every earlier one produced.

AST fuzzer (amd_release, oracle), 2026-09-17 06:58Z, STID 4827-5d4a, sha
71f5cde010d02c3a6078a366a6303a0e135a9441:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=120422&sha=71f5cde010d02c3a6078a366a6303a0e135a9441&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29

The shape is the one in my query above: merge() over children whose x types disagree (UInt32,
LowCardinality(UInt32) and Array(UInt32) in the fuzzer's database), an explicit PREWHERE, and
every column reference sitting inside an arrayMap lambda. Three reader threads took
Received signal 11 ... Address: NULL pointer. Access: read. inside
ExecutableFunctionVariantAdaptor::executeImpl, under
MergeTreeRangeReader::executePrewhereActionsAndFilterColumns. The server went down.

Why the failure site differs from the arms in this PR: with no common type across the children the
Merge level column becomes Variant(...), and that mismatch is not the one
ColumnFunction::appendArgument rejects. It reaches the Variant adaptor, whose
assert_cast<const ColumnVariant &> compiles to a plain static_cast outside debug and sanitizer
builds, so a release build reads ColumnVariant members off a ColumnUInt32.

One caveat, stated rather than glossed: the reachability and the shape match, but I have not reproduced
that adaptor route locally yet, so I am recording this alongside the capture-check arms rather than
asserting the two sites are one bug.

I am not reopening this and I am not asking for anything beyond the question already pending above.
Recording it because "it aborts in the reader" understates what the unrefused query does in a release
build.

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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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