Repository navigation
Conversation
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.
Internal second-model review: adjudication log (click to expand)Reviewed cold against the resulting code, then re-reviewed by an independent model (engine: codex)
Noted, not blocking:
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260813-203800 |
|
Workflow [PR], commit [39164d6] Summary: ❌
AI ReviewSummaryThis PR fixes several real lambda-related Tests
Final VerdictLLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 102/123 (82.93%) · Uncovered code |
Pre-PR validation gate (click to expand)
|
|
cc @yakov-olkhovskiy @novikd, could you review this? The PREWHERE column collection skipped |
|
|
||
| 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 } |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes7 object files changed (+47.31 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units77 translation units recompiled, 593 s compile time in total, 77 of them have a recent master baseline. |
CI finish ledger - 39164d6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head: 177 leaves, 159 success / 17 skipped / 1 failure, 0 dropped jobs.
On the one failure: the fuzzer mutated this PR's own new fixture tables, so it looks PR-caused, 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 Session id: cron:our-pr-ci-monitor:20260814-133000 |
|
Fixing PR for the |
|
This is not going to be supported |
|
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 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: If you want that refusal, it is the |
|
Another sighting of this hole, and this one changed severity class: a segmentation fault in a release
The shape is the one in my query above: Why the failure site differs from the arms in this PR: with no common type across the children the One caveat, stated rather than glossed: the reachability and the shape match, but I have not reproduced I am not reopening this and I am not asking for anything beyond the question already pending above. |
Related: #114206
Changelog category (leave one):
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_BLOCKerror when aPREWHEREexpression 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 supportedPREWHEREcolumns, so aMergewhose children declare it with different types built the filter against the wrong one rather than refusing it. Also fixesUNKNOWN_FUNCTIONfor aPREWHEREexpression calling an executable or WebAssembly UDF that does not itself read aJOINcolumn.Description
CollectPrewhereTableExpressionVisitor::needChildVisitskippedLAMBDA, so a column read only inside a lambda body never reachedvisitImpl, the one place that picks the table expressionPREWHEREreads from and enforcessupportedPrewhereColumns. On master:Mergewhose children declarexasUInt32andNullable(UInt32)excludesxfrom 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'sColumnFunctioncapture fails in the reader:Cannot capture column N ... incompatible type, a logical error, so an abort under sanitizers.PREWHEREis pinned to the first table expression, so a lambda over another failsCode: 10(Code 10NOT_FOUND_COLUMN_IN_BLOCKfor a right-side join column inside a lambda inPREWHERE#114206).The fix descends into lambda bodies, skipping only the lambda's own parameters by testing for a
LAMBDA_ARGScolumn source, as the siblingCollectSourceColumnsVisitoralready does: a node type, not a function name, so all higher-order functions are covered.Collecting those columns makes two latent omissions live.
ReplaceColumnsVisitornever entered a lambda either, so theJOINtype substitution thatPREWHEREmust roll back survived inside a lambda and aborted atjoin_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 theUNKNOWN_FUNCTION. It is now bounded to replaced subtrees, so a UDF reading a restoredJOINcolumn stays refused as on master.Reported by @ nikitamikhaylov on #113768: one
Server diedin that PR's unrelated Stress test (amd_msan), report.Validation
Reproducer (aborts on master,
ILLEGAL_PREWHEREwith this change):04879_prewhere_lambda_body_column_check: 29 arms A/B'd against a base build, 8 refusals and21 row-returning. Every refusal and every
join_use_nullsshape is paired with the same querywithout a lambda, so each expected outcome is justified against master's own answer.
m.x(also*,arrayFilter)ILLEGAL_PREWHEREARRAY JOINed alias inside a lambdaCode: 10ILLEGAL_PREWHEREJOINCode: 10LEFT JOIN, right column inarrayExists,join_use_nulls0 and 1 (#114206)Code: 101/2WHERE; unrestricted table; shadowed parameter04889_prewhere_lambda_executable_udfcovers the UDF case in 9 arms, with a built-in control.Five mutation arms, disjoint casualties: reverting
needChildVisitre-introduces the abort andthe
Code: 10; dropping theLAMBDA_ARGSguard breaks04108; revertingReplaceColumnsVisitoraborts inActionsDAG; dropping either return-type refresh or theparameter-type re-derivation aborts in planning or in
ColumnFunction::appendArgument.04108,03036_prewhere_lambda_function,00729_prewhere_array_joinand02955_analyzer_using_functional_argspass unchanged. Both new tests ran 50x, 0 failures:04879under randomized settings,04889atclickhouse-localdefaults.