Skip to content

Do not move a non-deterministic expression below ARRAY JOIN - #117756

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix-lift-up-array-join-nondeterministic-117263
Sep 6, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix-lift-up-array-join-nondeterministic-117263

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

liftUpArrayJoin moves the part of a filter or an expression that does not depend on the ARRAY JOIN-produced columns below the ARRAY JOIN, and ActionsDAG::splitActionsBeforeArrayJoin decided what to move by data dependency alone - the pass had no determinism check at all. ARRAY JOIN multiplies the rows, so an expression that is not deterministic within the query was drawn once per source row instead of once per expanded row, and a filter over it kept or dropped whole arrays at once:

SELECT countIf(c NOT IN (0, 4)) FROM (
  SELECT g, count() AS c FROM (
    SELECT number AS g, arr FROM (SELECT number, range(4) AS arr FROM numbers(100))
    ARRAY JOIN arr
    WHERE rand(g) % 2 = 0
  ) GROUP BY g
);
-- always 0; ~85 with query_plan_lift_up_array_join = 0

Such an expression is now treated as depending on the ARRAY JOIN, so it stays where the query wrote it. Deterministic expressions are moved as before, which the test asserts with EXPLAIN.

The same holds for a higher-order function with a non-deterministic or stateful lambda, such as arrayExists(x -> rand() % 2 = 0, arr): a lambda (FunctionCapture, and the FunctionExpression behind the constant a lambda without captured columns is folded into) now reports isDeterministic, isDeterministicInScopeOfQuery and isStateful from the functions in its body, and the ARRAY JOIN split, the filter pushdown (getConjunctionNodes) and hasStatefulFunctions look through such constant lambda columns. Both the lift-up and the pushdown route across the ARRAY JOIN are covered by the tests.

Closes: #117263

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 to CHANGELOG.md):

Fixed a filter containing a non-deterministic function being moved below ARRAY JOIN, which evaluated it once per source row instead of once per expanded row and made whole arrays pass or fail together.


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

Version info

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

`liftUpArrayJoin` moves the part of a filter or an expression that does not depend on the
`ARRAY JOIN`-produced columns below the `ARRAY JOIN`, and
`ActionsDAG::splitActionsBeforeArrayJoin` decided what to move by data dependency alone.
`ARRAY JOIN` multiplies the rows, so an expression that is not deterministic within the
query was drawn once per source row instead of once per expanded row, and a filter over it
kept or dropped whole arrays at once.

Such an expression is now treated as depending on the `ARRAY JOIN`, so it stays where the
query wrote it. Deterministic expressions are moved as before.

Closes: #117263
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4f223c8]

Summary: ✅


AI Review

Summary

This PR fixes the plan-based ARRAY JOIN lift-up / filter-pushdown bug for non-deterministic higher-order lambdas, and I verified that the earlier inline concern about those lambdas is addressed in the current code. I do not think it is ready to merge yet because the same wrong-result class is still reachable through the supported enable_analyzer = 0 path.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:826-863] [dismissed by author -- https://github.com/Do not move a non-deterministic expression below ARRAY JOIN #117756#issuecomment-5558797988] The PR contract is broader than the implementation: with enable_analyzer = 0, MergeTreeWhereOptimizer::cannotBeMoved still has no determinism or statefulness screen, so a WHERE over ARRAY JOIN can still be moved into Before ARRAY JOIN / PREWHERE and evaluated once per source row instead of once per expanded row. The current code here still only blocks arrayJoin, GLOBAL IN, and direct references to joined-column names, so the original wrong-result behavior remains reachable under a supported compatibility setting.
    Suggested fix: mirror the new non-deterministic / stateful guard in the legacy mover (or disable this optimization for ARRAY JOIN queries when a conjunct is not deterministic in scope of query), and add a focused enable_analyzer = 0 regression.
Tests
  • ⚠️ Add one stateless regression with enable_analyzer = 0 that proves a non-deterministic WHERE on an ARRAY JOIN query is not moved into Before ARRAY JOIN / PREWHERE; the discussion already contains a minimal repro.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 4f223c8.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 53/55 (96.36%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

The fix is exact for the pass it targets, and the pre-existing determinism guard in getConjunctionNodes is what keeps the filter-pushdown route safe without a change here. Two completeness notes.

  1. On the captured-lambda gap flagged above: it is not specific to splitActionsBeforeArrayJoin. getConjunctionNodes (ActionsDAG.cpp:3230) applies the same per-node function_base->isDeterministicInScopeOfQuery() test, and FunctionCapture (FunctionsMiscellaneous.h:238) overrides only isSuitableForConstantFolding (which does walk its inner DAG) — it overrides neither isDeterministicInScopeOfQuery nor isStateful, so it reports the base-class true. Consequently arrayExists(x -> rand() % 2 = 0, arr2) written above the ARRAY JOIN would be pushed below it by the filter pushdown through ArrayJoinStep even if this split learned to descend into captured DAGs. Teaching FunctionCapture to report its inner DAG's determinism and statefulness closes both routes at once; a descend-from-the-split variant closes only one.

  2. The same once-per-source-row collapse survives in the legacy path through a different placement: with enable_analyzer = 0, the WHERE over an ARRAY JOIN query is placed as a "Before ARRAY JOIN" filter (and, when the condition is PREWHERE-eligible, as a Prewhere filter under ReadFromMergeTree), so a non-deterministic condition is evaluated once per source row before expansion. EXPLAIN actions = 1 on SELECT g, c FROM t ARRAY JOIN arr AS c WHERE rand(g) % 2 = 0 SETTINGS enable_analyzer = 0, query_plan_optimize_prewhere = 0 shows Prewhere filter column: rand(g) MOD 2 = 0 beneath the ArrayJoin step. MergeTreeWhereOptimizer::cannotBeMoved has no determinism screen, so this is the same missing-check class in the legacy mover; probably a follow-up since it needs the non-default legacy path.

For cross-reference, this fixes the plan-level query_plan_lift_up_array_join leg reported in #117263.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +9.0 s (+9%) in total before that adjustment.

Job report

@yariks5s yariks5s self-assigned this Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
The guard in `splitActionsBeforeArrayJoin` only looked at the outer `FUNCTION` node, so a
higher-order function with a non-deterministic or stateful lambda, such as
`arrayExists(x -> rand() % 2 = 0, arr)`, was still moved across the `ARRAY JOIN` and its lambda
was drawn once per source row instead of once per expanded row. The filter pushdown through
`ArrayJoinStep` (`getConjunctionNodes`) had the same gap.

A lambda now reports `isDeterministic`, `isDeterministicInScopeOfQuery` and `isStateful` from the
functions in its body, both as a `FunctionCapture` (a lambda with captured columns, a `FUNCTION`
node) and as a `FunctionExpression` (the function of the `ColumnFunction` that constant folding
turns a lambda without captured columns into, a `COLUMN` node). `splitActionsBeforeArrayJoin`,
`getConjunctionNodes` and `hasStatefulFunctions` look through such constant lambda columns, and
through the lambdas nested in them as captured columns, so both routes across the `ARRAY JOIN`
are closed.

Addresses the review on #117756.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1, thank you. On (1): done in 4f223c8 the way you suggested, on the lambda itself rather than in the split. FunctionCapture and FunctionExpression now report isDeterministic, isDeterministicInScopeOfQuery and isStateful from their body, and splitActionsBeforeArrayJoin, getConjunctionNodes and hasStatefulFunctions also look through the ColumnFunction constant that a lambda without captured columns is folded into (including lambdas nested in it as captured columns). That closes both the lift-up and the pushdown route; 05099_lift_up_array_join_nondeterministic_lambda covers them. I deliberately did not stop folding such lambdas into constants: 02354_vector_search_nonindexed_columns relies on arrayMap(i -> randCanonical(i), range(16)) being one constant reference vector for the whole query, so that stays as is.

On (2), the legacy analyzer placing a non-deterministic WHERE as a filter before ARRAY JOIN / in PREWHERE: agreed that it is the same class, but it is a separate mover (MergeTreeWhereOptimizer and the legacy ExpressionAnalyzer chain), so I am leaving it for a follow-up rather than growing this fix.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
Merged via the queue into master with commit 8201c82 Sep 6, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-lift-up-array-join-nondeterministic-117263 branch September 6, 2026 20:41
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 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.
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 10, 2026
The expression-merge optimization refuses to fuse a parent expression
into a child DAG that contains `arrayJoin` only when the parent has
stateful functions. A merely non-deterministic parent (`rand64`,
`generateUUIDv4`, ...) passed that gate and was then computed before the
row replication: one draw per source row, replicated across all the rows
the `arrayJoin` expands, instead of one draw per output row.

    SELECT uniqExact(r), count()
    FROM (SELECT rand64() AS r FROM (SELECT arrayJoin(range(4)) AS x FROM numbers(100)));
    -- 100  400, each draw repeated on all four expanded rows

The gate now declines a parent that is non-deterministic within the
query as well, using the same predicate the `ArrayJoinStep` routes
adopted in ClickHouse#117756: `now`/`today`/`currentUser` are deterministic in the
scope of a query and still merge.
alexey-milovidov added a commit that referenced this pull request Sep 10, 2026
…minism-filter-pushdown-117262

The source fix of this branch landed on master meanwhile, in a more general
form, through #117756 (`Keep a non-deterministic lambda on its side of
\`ARRAY JOIN\` too`): `FunctionCapture` and `FunctionExpression` derive
`isDeterministic`, `isDeterministicInScopeOfQuery` and `isStateful` from the
functions of their body, the walk recurses into `COLUMN` nodes holding a
`ColumnFunction` and into the lambdas nested in them as captured columns, and
`getConjunctionNodes` uses that shared walk (`allNodeFunctions`).

Both conflicts are therefore resolved in favour of master: this branch's
`lambdaBodySatisfies` and `columnHoldsNonDeterministicLambda` are dropped as
duplicates of the shared helpers in `src/Functions/FunctionsMiscellaneous.h`.
The regression test of the aggregation route, which no test on master covers,
is kept.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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 Sep 15, 2026
…mber

The control arm of 05054_deduplicated_rows_need_query_determinism pinned
`rowNumberInBlock()` over `ARRAY JOIN` to `[0,0,1,1]`, which is the numbering of
the source rows, before the replication. ClickHouse#117756 made
`ActionsDAG::splitActionsBeforeArrayJoin` treat a node that is stateful or not
deterministic in the scope of the query as depending on the `ARRAY JOIN`, so
`liftUpArrayJoin` no longer moves this control below it: the function sees the
expanded block and reports `[0,1,2,3]`. Merging master into this branch is what
turned Fast test red, on that one line.

Re-freezing the literal would pin the plan's block layout, which is the class of
output this change is about in the first place. The control is here to show that
a function with no argument has nothing to compress, so the lazy and the eager
representation must agree; that agreement, plus the row count, is now the
assertion, and neither arm's sequence is pinned.

Measured at 134b858, build a0053ff1cadbced4: the tree as published fails on
that one line and on nothing else, the new form passes 30 of 30 randomized runs,
and it is not stuck at true, since splitting the second arm into two-row blocks
prints `0 1` and shortening one arm's LIMIT prints `0 0`. On master without this
branch (45efaa4) the control prints `1 1` while `runningAccumulate` over the
same fixture still differs between the arms, so the control stays green on the
base binary, as a control must.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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

Development

Successfully merging this pull request may close these issues.

query_plan_lift_up_array_join moves a non-deterministic filter below ARRAY JOIN with no determinism check

4 participants