Repository navigation
See non-determinism inside a lambda body in the plan-time join conversions - #117248
Conversation
…sions `convertOuterJoinToInnerJoin` and `convertAnyJoinToSemiOrAntiJoin` decide by evaluating the filter over fabricated one-row inputs, guarded by `dagContainsNonDeterministicFunction`. The guard walked the outer DAG only. A non-deterministic call that depends on a lambda argument - `rand(x)` in `arrayExists(x -> rand(x) % 2 = 0, ...)` - stays inside the lambda's own `ActionsDAG`, so a single plan-time draw decided whether `LEFT` became `INNER` and `ANY LEFT` became `SEMI`. Half of the runs got a plan that dropped every not-matched row: the same query returned ~500 or ~5 rows. Two things were missing. `FunctionCapture` and `FunctionExpression` did not answer for their inner DAG, the way `FunctionCapture::isSuitableForConstantFolding` already does; and a lambda that captures no columns has no arguments at all, so it is folded into a `COLUMN` node holding a `ColumnFunction` that the guard's function-node loop never looked at. Closes: #117016
|
Workflow [PR], commit [9b5351a] Summary: ✅
AI ReviewSummaryThis PR closes the lambda-body non-determinism blind spot in the plan-time Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 9b5351a.
Changed lines: Changed C/C++ lines covered: 47/55 (85.45%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units21 translation units recompiled, 157 s compile time in total, 21 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too. |
…-lambda-nondeterminism
… settings the test asserts `innerDAGFunctionsSatisfy` walked only the `FUNCTION` nodes of the lambda's own DAG, so a nested lambda that captures nothing - folded into a `COLUMN` node holding a `ColumnFunction` - hid its body again: `arrayExists(x -> arrayExists(y -> rand(y) % 2 = 0, materialize([1])), materialize([1]))` still answered `isDeterministicInScopeOfQuery() == true`. The helper, now `dagFunctionsSatisfy`, also asks the captured function of such a `COLUMN` node, which answers for its own inner DAG and so recurses to any depth; `dagContainsNonDeterministicFunction` reuses it instead of repeating the top-level check. The test failed in CI on its positive control: the harness turns `query_plan_convert_outer_join_to_inner_join` and `query_plan_convert_any_join_to_semi_or_anti_join` off at random, and the conversions are analyzer plan-level, so the control was a coin flip and always 0 in the old-analyzer job. The test now asks for the plan it asserts. Renumbered to `05059`, and it covers the nested shape - both the non-deterministic body and a deterministic one, which must still convert.
Master fixed the main filter push-down and the step-level stateful veto in 4f223c8 (ClickHouse#117756): getConjunctionNodes and hasStatefulFunctions now go through allNodeFunctions, which enters a lambda body, so the ActionsDAG.cpp and filterPushDown.cpp changes here are redundant and the local lambdaBodySafety helper has no remaining caller. The Utils.cpp guard on dagContainsNonDeterministicFunction is conceded to ClickHouse#117248, whose replacement expression is character-identical to the one this branch carried, and which ships its own test and credits issue ClickHouse#117016. partialJoinFilterPushDown.cpp is reverted here too, so this commit compiles on its own once the helper is gone; the next commit re-adds the guard in master's own idiom.
…-lambda-nondeterminism
…scope of a query A lambda that captures no non-constant column is folded into a constant `ColumnFunction`, which makes the higher-order function around it constant as well when its other arguments are constant. A constant is evaluated once and its value is reused for the whole query, so a non-deterministic call in the lambda body was drawn a single time and decided every row: `WHERE arrayExists(y -> rand(y) % 2 = 0, [1])` over 3 million rows returned either 0 or 3000000, while `rand(y) % 2 = 0` outside a lambda is drawn per row. `FunctionCapture::isSuitableForConstantFolding` walked the lambda body for foldability only, and it did not look at a nested lambda that constant folding had already turned into a `COLUMN` node holding a `ColumnFunction`. The walk is now shared with `FunctionExpression` - the function such a carrier holds - so it recurses through the carriers at every nesting level, and it also requires every function of the body to be deterministic in the scope of a query. This addresses the review finding on the constant-folding side of the same nested-lambda carrier that `dagContainsNonDeterministicFunction` had to look through. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… deterministic The test built the reference vector with `arrayMap(i -> randCanonical(i), range(16))`. Such a lambda body is not deterministic in the scope of a query, so it is no longer constant folded, and the reference vector of a vector search has to be a constant for the index to be used: `useVectorSearch` reads it from a `COLUMN` node of the sort expression. Both `EXPLAIN indexes = 1` queries of the test therefore stopped printing `Description: vector_similarity GRANULARITY 100000000`, which is the only difference the test reported. This matches what a non-deterministic reference vector already did outside a lambda - `rand` with a constant argument is folded into a constant node marked non-deterministic, which the planner expands back into the function - so the vector index was never usable for a genuinely random reference vector. The lambda form was the one exception, and it went away together with the frozen single draw it was based on. The reference vector is now `arrayMap(i -> i / 16, range(16))`, which keeps the intent of the test (filter strategies over an indexed and a non-indexed vector column) and its reference output unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…-lambda-nondeterminism
Address review: the same `COLUMN(Const(ColumnFunction))` carrier that `dagContainsNonDeterministicFunction` now looks into was still invisible to three other walks, all of which inspected `FUNCTION` nodes only: - `ReadFromMergeTree::isNodeDeterministic`, which gates `isRowPolicyDeferredAfterFinal`; - `VirtualColumnUtils::isDeterministicInScopeOfQuery` (and its sibling `isDeterministic`), which gates the min/max projection shortcut; - `collectConditionInputs` in the `AggregationPushdown` cascades rule. They all reuse the shared `allNodeFunctions` helper now. Only the row-policy one is reachable in practice, and it is reachable for a body that is *not* deterministic rather than one that is not deterministic in scope of the query: this pull request's own constant-folding gate requires every body function to satisfy `isSuitableForConstantFolding` **and** `isDeterministicInScopeOfQuery`, so a surviving carrier is in-scope-deterministic by construction, but it can still hold e.g. `randConstant`. Measured with a control binary: a row policy `USING arrayExists(z -> randConstant(z) % 2 = 0, [x])` on a `ReplacingMergeTree` reports zero `Deferred row level filter` lines before the change and one after, i.e. it used to be evaluated before `FINAL`, which can keep a version that evaluating the policy after `FINAL` would have dropped. `05182_row_policy_after_final_lambda_nondeterminism` pins that, with a deterministic lambda of the same shape as the negative control. The other two walks are in-scope-of-query checks, so the folding gate already makes the reported scenario unreachable; keeping them in sync with `dagContainsNonDeterministicFunction` is defense in depth and costs nothing. `isNodeDeterministic` additionally honours `ActionsDAG::Node::isDeterministic` now, so a constant folded from `now` no longer slips past it either - `VirtualColumnUtils::isDeterministic` already did that. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 The The abort is Fixed by #119385, which names this exact The second reported item, Related: #119385 |
|
📊 Cloud Performance Report ✅ AI verdict: This PR only tightens how the analyzer detects non-deterministic calls hidden inside lambda bodies (constant-folding of higher-order functions across JOIN conversion, PREWHERE/MergeTree determinism checks, virtual-column and row-policy handling). None of the flagged ClickBench queries (Q16, Q30, Q31, Q34) use lambdas, higher-order functions, joins, or non-deterministic predicates, so their execution paths are untouched by these changes. Q16's flagged +11.9% regression is downgraded to not_sure because the diff cannot plausibly affect a plain GROUP BY UserID scan, and its history is noisy. The three within-envelope rows (Q30/Q31/Q34) were correctly suppressed deterministically and are consistent with run-to-run variance on these noisy queries. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
The source fix of this pull request landed on `master` through #117756 and #117248, and the latter also brought a row policy test with the same shape as `05188_row_policy_after_final_nondeterministic_lambda` (`05182_row_policy_after_final_lambda_nondeterminism`), so that test is dropped. The aggregation push-down test and the file pruning test are renumbered to a free range, since `05187` and `05189` were claimed on `master` meanwhile. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`StorageSet::insertBlock` inserts into the very `Set` object a running query holds (`FutureSet::isMutableDuringQuery`), so a policy such as `k IN set_table` can give two versions of one key different verdicts when an `INSERT` into the `Set` table lands between the reads of their parts, and FINAL then returns a superseded version. On master such a policy stays after FINAL only because ClickHouse#117248 rejected every constant folded from a non-deterministic expression, and the set of any `IN` is marked that way; dropping that check would have moved it before FINAL. Refuse a `ColumnSet` whose set is mutable during the query, also when a folded lambda captures it (`arrayExists(x -> x IN set_table, [k])`), where the planner passes the set to the lambda as a captured column. The set of `IN (subquery)` is built once by the query and frozen, so it is still applied before FINAL. Also reword the setting description: such a query-wide value is still marked non-deterministic, it just no longer prevents the optimization. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClickHouse#117248 made `isNodeDeterministic` also reject a `COLUMN` node whose `is_deterministic_constant` flag is false. The analyzer sets that flag to false for a constant folded from a non-deterministic function, so a row policy like `c2 = substring(currentUser(), 1, 3)` over `ORDER BY` columns started to look non-deterministic. `isRowPolicyDeferredAfterFinal` then deferred it after `FINAL`, and PREWHERE with it, so the whole table was read and merged before the policy filtered it (ClickHouse#130317: 9.7x memory, 2.7x time on 26.10 against 26.8). The same happened for `now()`, `currentDatabase()` and `IN (subquery)` sets. Before FINAL the policy only has to give every version of one key the same verdict. A constant has one value for the whole query, so it cannot split a dedup group, whatever its cross-query determinism. Only a lambda folded into a constant is evaluated per row, and `allNodeFunctions` plus the carrier check below it still look into its body, so the ClickHouse#117248 cases (05141, 05182) stay deferred. The flag itself is unchanged: the query condition cache still needs it. Closes ClickHouse#130317 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #117016
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix the plan-time join conversions (
LEFTtoINNER,ANYtoSEMI/ANTI) silently dropping rowswhen the filter above the join contains a non-deterministic function inside a lambda body, and stop
constant folding a lambda whose body is not deterministic in the scope of a query, which reused a
single draw of e.g.
randfor every row of the query.Description
convertOuterJoinToInnerJoinandconvertAnyJoinToSemiOrAntiJoindecide the conversion byevaluating the filter over fabricated one-row inputs, guarded by
dagContainsNonDeterministicFunction.The guard only looked at the outer DAG's function nodes, so a non-deterministic call that depends on a
lambda argument was invisible: it lives in the lambda's own
ActionsDAG, and a lambda that captures nonon-constant column is folded into a
COLUMNnode holding aColumnFunctionrather than staying aFUNCTIONnode. The guard now uses the shared walk ofFunctionsMiscellaneous.h, which looks throughthose carriers at every nesting level.
Before:
SELECT count() FROM t1 ANY LEFT JOIN t2 ON t1.k = t2.k WHERE t2.v = 12345 OR arrayExists(x -> rand(x) % 2 = 0, materialize([1]))returned
511 5 8 499 6 …across runs — the small values are plans converted toSEMI, which dropthe 990 not-matched rows before the runtime filter ever sees them. After:
511 501 507 503 502 523.The same carrier had a second, independent consequence, found in review. A folded lambda is a constant
ColumnFunction, which makes the higher-order function around it constant as well when its otherarguments are constant, and a constant is evaluated once and reused for the whole query. So a
non-deterministic call in the body was drawn a single time and decided every row:
isLambdaBodySuitableForConstantFoldingis now shared byFunctionCaptureandFunctionExpression,so it recurses through the folded carriers, and it requires every function of the body to be both
suitable for constant folding and deterministic in the scope of a query. A deterministic lambda over a
constant array is still folded.
One existing test had to be adapted:
02354_vector_search_nonindexed_columnsbuilt its reference vectorwith
arrayMap(i -> randCanonical(i), range(16)). A vector index is only used when the reference vector isa constant -
useVectorSearchreads it from aCOLUMNnode of the sort expression - so that lambda is nolonger folded and the two
EXPLAIN indexes = 1queries stopped printing thevector_similaritydescription.Outside a lambda this was already the case (
randwith a constant argument is folded into a constant nodemarked non-deterministic, which the planner expands back into the function), so the test now uses the
deterministic
arrayMap(i -> i / 16, range(16))and its reference output is unchanged.Tests:
05059_join_conversion_nondeterministic_lambdacoversANY LEFTandLEFT, a lambda nested inanother lambda, and that a deterministic lambda still allows the conversion;
05166_nondeterministic_nested_lambda_constant_foldingcovers the constant-folding half.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117248]
Version info
26.9.1.1377(included in26.9and later)