Skip to content

See non-determinism inside a lambda body in the plan-time join conversions - #117248

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix-join-conversion-lambda-nondeterminism
Sep 13, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix-join-conversion-lambda-nondeterminism

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117016

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 the plan-time join conversions (LEFT to INNER, ANY to SEMI/ANTI) silently dropping rows
when 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. rand for every row of the query.

Description

convertOuterJoinToInnerJoin and convertAnyJoinToSemiOrAntiJoin decide the conversion by
evaluating 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 no
non-constant column is folded into a COLUMN node holding a ColumnFunction rather than staying a
FUNCTION node. The guard now uses the shared walk of FunctionsMiscellaneous.h, which looks through
those 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 to SEMI, which drop
the 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 other
arguments 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:

SELECT count() FROM numbers_mt(3000000) WHERE arrayExists(y -> rand(y) % 2 = 0, [1]);
-- before: 0, then 3000000, then 3000000; the control `WHERE rand(number) % 2 = 0` gives ~1500000

isLambdaBodySuitableForConstantFolding is now shared by FunctionCapture and FunctionExpression,
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_columns built its reference vector
with arrayMap(i -> randCanonical(i), range(16)). A vector index is only used when the reference vector is
a constant - useVectorSearch reads it from a COLUMN node of the sort expression - so that lambda is no
longer folded and the two EXPLAIN indexes = 1 queries stopped printing the vector_similarity description.
Outside a lambda this was already the case (rand with a constant argument is folded into a constant node
marked 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_lambda covers ANY LEFT and LEFT, a lambda nested in
another lambda, and that a deterministic lambda still allows the conversion;
05166_nondeterministic_nested_lambda_constant_folding covers the constant-folding half.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.9.1.1377 (included in 26.9 and later)

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

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9b5351a]

Summary: ✅


AI Review

Summary

This PR closes the lambda-body non-determinism blind spot in the plan-time JOIN conversions and also fixes the related constant-folding and apply_row_policy_after_final cases that came up during review. I re-read the current diff, the touched helpers, and every prior review-thread reply against the current code, and I did not find a remaining correctness issue that warrants a new inline comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 9b5351a.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 47/55 (85.45%) · 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 31, 2026
Comment thread src/Functions/FunctionsMiscellaneous.h Resolved

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Overall LGTM

Comment thread src/Functions/FunctionsMiscellaneous.h Resolved
@novikd novikd self-assigned this Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9b5351acb with master b1b138da3 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of bdbd87dd4; 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.

Compile time of recompiled translation units

21 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.
The matched translation units cost +9.3 s (+6%) in total before that adjustment.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too.

… 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.
Comment thread src/Functions/FunctionsMiscellaneous.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 8, 2026
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.
alexey-milovidov and others added 2 commits September 10, 2026 03:37
…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]>
alexey-milovidov and others added 3 commits September 10, 2026 18:33
… 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]>
Comment thread src/Functions/FunctionsMiscellaneous.h Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (amd_tsan) red on 851c285 is unrelated to this pull request and already has a fix in flight.

The abort is Logical error: Virtual row has different type for CAST(__table1.json.b, 'String'_String). Expected ... Nullable(String) ..., got ... String ... in setVirtualRow (src/Processors/Merges/Algorithms/MergeTreeReadInfo.cpp:70), from 03277_json_subcolumns_in_primary_key running select * from test order by json.a, json.b::String, id with the stress randomizer's cast_keep_nullable = 1. The sorting key expression resolves to a different type in the query than in the table, and read-in-order treats the two as interchangeable. This diff only touches lambda determinism, constant folding and the plan-time determinism walks — it has nothing to do with virtual rows or sorting-key types.

Fixed by #119385, which names this exact LOGICAL_ERROR and the cast_keep_nullable trigger in its changelog entry. Once it lands on master, a merge here clears the red.

The second reported item, Logical error query with a numbers(10, sipHash64(...), sipHash64(...)) fuzzer query, is the memory_tracker_fault_probability = 0.05 injection in the same run, not a separate defect.

Related: #119385

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 537 601 +11.9% <0.0001 aggregation: Q16 is a plain GROUP BY UserID aggregation with no joins, lambdas, higher-order functions, or non-deterministic calls, so the lambda/constant-folding determinism changes cannot touch its hot path; the +11.9% on a noisy query is run-to-run variance.
⚠️ 30 not_sure 226 257 +13.7% <0.0001 aggregation: Within-envelope call is sound. Q30 is a GROUP BY aggregation with no lambdas or non-deterministic predicates; this PR's determinism-walk changes cannot touch it, and the query is noisy, so the +13.7% reads as variance.
⚠️ 31 not_sure 267 319 +19.5% <0.0001 aggregation: Within-envelope call is sound. Q31 is a GROUP BY aggregation untouched by the lambda determinism changes; noisy history explains the +19.5% swing as variance.
⚠️ 34 not_sure 1142 1210 +5.9% <0.0001 aggregation: Within-envelope call is sound. Q34 (large SUM expression aggregation) has no lambdas or joins the PR's constant-folding walk affects; the +5.9% is within the variance band.

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
  • StressHouse run: 31a76277-ebe7-4d22-ae9b-0dd89441075f
  • MIRAI run: 52790dc3-f141-49bf-b421-a38c34b086ca
  • PR check IDs:
    • clickbench_206270_1789236153
    • clickbench_206276_1789236153
    • clickbench_206287_1789236153
    • tpch_adapted_1_official_206293_1789236153
    • tpch_adapted_1_official_206310_1789236153
    • tpch_adapted_1_official_206341_1789236153

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into master with commit 0accc25 Sep 13, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-join-conversion-lambda-nondeterminism branch September 13, 2026 08:03
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
alexey-milovidov added a commit that referenced this pull request Sep 14, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 11, 2026
`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]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 13, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants