Skip to content

Fix optimize_move_to_prewhere moving non-deterministic functions to PREWHERE under FINAL - #109538

Merged
yariks5s merged 33 commits into
masterfrom
yarik/fix-prewhere-final-nondeterministic
Sep 18, 2026
Merged

yariks5s merged 33 commits into
masterfrom
yarik/fix-prewhere-final-nondeterministic

Conversation

@yariks5s

@yariks5s yariks5s commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

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 bugs where non-deterministic conditions were moved to PREWHERE under FINAL + optimize_move_to_prewhere optimization

Validation:

DROP TABLE IF EXISTS t_proof;
CREATE TABLE t_proof (k Int32, data String, v UInt64) ENGINE = ReplacingMergeTree(v) ORDER BY k;
INSERT INTO t_proof SELECT number, 'old', 1 FROM numbers(10000);
INSERT INTO t_proof SELECT number, 'new', 2 FROM numbers(10000);

-- Counts rows returned by `FINAL WHERE <random predicate>` that do not exist in FINAL at all.
-- For every possible outcome of rand() this must be 0: the filter may pick an arbitrary
-- subset of FINAL's rows, but it can never emit a row that is not in FINAL.
SELECT count() AS rows_not_in_final
FROM (SELECT * FROM t_proof FINAL WHERE (k + rand()) % 2 = 0) AS filtered
LEFT ANTI JOIN (SELECT * FROM t_proof FINAL) AS final_rows USING (k, data, v)
SETTINGS optimize_move_to_prewhere_if_final = 1;


┌───────────────────────────────────────────────────────────────┬───────────────────┐
│                                                               │ rows_not_in_final │
├───────────────────────────────────────────────────────────────┼───────────────────┤
│ optimize_move_to_prewhere_if_final = 0                        │ 0                 │
├───────────────────────────────────────────────────────────────┼───────────────────┤
│ optimize_move_to_prewhere_if_final = 1, build without the fix │ 2532              │
├───────────────────────────────────────────────────────────────┼───────────────────┤
│ optimize_move_to_prewhere_if_final = 1, build with the fix    │ 0                 │
└───────────────────────────────────────────────────────────────┴───────────────────┘

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

@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f52cb6]

Summary: ✅


AI Review

Summary

This PR fixes real FINAL correctness bugs on the planner path by teaching the PREWHERE and row-policy determinism checks to look through lambda captures and folded ColumnFunction carriers. The remaining problem is test coverage: the current patch no longer proves the old AST PREWHERE path, even though that path is still live for old-interpreter / shard-side execution.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04500_prewhere_final_nondeterministic_condition.sql:4-6] The built-in rand regression is still only covered with query_plan_optimize_prewhere = 1, so the FunctionFactory::tryGet(...)->isDeterministicInScopeOfQuery() branch in src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:809-829 remains unproven. That AST path is not dead code: src/Interpreters/executeQuery.cpp:2299-2302 still preserves allow_experimental_analyzer = 0 for non-local SECONDARY_QUERY, src/Interpreters/InterpreterFactory.cpp:146-151 still routes such queries to InterpreterSelectQuery, and src/Interpreters/InterpreterSelectQuery.cpp:920-977 still runs MergeTreeWhereOptimizer::optimize there. Suggested fix: restore a focused shard-side / old-interpreter regression that proves FINAL WHERE (k + rand()) % 2 = 0 does not become PREWHERE on that path.

  • [tests/queries/0_stateless/04506_wasm_udf_prewhere_final.sh:37-39] The same coverage gap exists for the UDF-specific fallback added in src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:817-825. The current file only exercises EXPLAIN actions=1 on the planner path, so a regression in the AST lookup for deterministic vs non-deterministic WASM / executable UDFs would pass CI as long as the planner path stays correct. Suggested fix: keep an old-interpreter assertion for deterministic and non-deterministic WASM predicates under FINAL instead of dropping that branch entirely.

Final Verdict

Changes to the determinism logic look correct on the current head, but the PR is not ready to merge with the AST-path regression coverage removed.

LLVM Coverage Report

Measured on commit 0f52cb6.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 41/55 (74.55%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 6, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Updating the branch to fix the 04001_join_reorder_through_expression test, which was broken today in master.

SET explain_query_plan_default = 'legacy';
SET enable_analyzer = 1;
SET optimize_move_to_prewhere = 1;
SET query_plan_optimize_prewhere = 1;

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.

This still doesn't exercise the code added in the last two commits. The whole file keeps query_plan_optimize_prewhere = 1, so it only checks the planner ActionsDAG path; there is no case that flips to the legacy AST PREWHERE path and runs a deterministic/non-deterministic WASM UDF on a sorting-key predicate. That means both the new AST fallback in isFunctionDeterministicInScopeOfQuery and the new FunctionUserDefinedWasm::isDeterministicInScopeOfQuery() override can regress without this test catching it. Please add a focused case for query_plan_optimize_prewhere = 0 plus deterministic and non-deterministic WASM filters under FINAL.

@novikd novikd self-assigned this Jul 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Updated the branch with the latest master (it was 11 days behind). Both CI failures on the previous run are known flaky logical errors unrelated to this PR:

SET explain_query_plan_default = 'legacy';
SET enable_analyzer = 1;
SET optimize_move_to_prewhere = 1;
SET query_plan_optimize_prewhere = 1;

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.

The generic rand() regression that motivated this PR is still only covered on the planner path. This file pins query_plan_optimize_prewhere = 1, and 04506 only exercises the legacy AST path through the UDF-specific branches. That leaves the FunctionFactory::tryGet(...)->isDeterministicInScopeOfQuery() fallback in isFunctionDeterministicInScopeOfQuery untested for built-in non-deterministic functions: if that lookup regresses, FINAL WHERE (k + rand()) % 2 = 0 can start moving to PREWHERE again with query_plan_optimize_prewhere = 0 and nothing in this patch will fail. Please add a small EXPLAIN SYNTAX / query_plan_optimize_prewhere = 0 case for a built-in predicate like rand().

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.

Added 04647_prewhere_final_nondeterministic_ast_path, which runs with enable_analyzer = 0 and query_plan_optimize_prewhere = 0 and asserts via EXPLAIN SYNTAX that FINAL WHERE (k + rand()) % 2 = 0 stays in WHERE (and that a deterministic sorting-key condition is still moved). That drives exactly the FunctionFactory::tryGet(...)->isDeterministicInScopeOfQuery() branch of isFunctionDeterministicInScopeOfQuery for a built-in non-deterministic function. Also merged the latest master (the branch was a week behind).

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.

The AST-path coverage is still missing on the current head. tests/queries/0_stateless/04500_prewhere_final_nondeterministic_condition.sql:4-7 hard-codes query_plan_optimize_prewhere = 1, and there is no remaining FINAL + built-in rand case with query_plan_optimize_prewhere = 0.

That matters because src/Interpreters/InterpreterSelectQuery.cpp:1099 still routes query_plan_optimize_prewhere = 0 through the AST-based MergeTreeWhereOptimizer::optimize, so the fallback added in src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:809-829 is again untested.

alexey-milovidov and others added 2 commits July 26, 2026 18:39
…tic functions

The AI review noted that `04500_prewhere_final_nondeterministic_condition`
pins `query_plan_optimize_prewhere = 1`, so the built-in `rand` regression
was only asserted on the planner path, and `04506` only drives the UDF
branches of the AST fallback. The
`FunctionFactory::tryGet(...)->isDeterministicInScopeOfQuery()` branch of
`isFunctionDeterministicInScopeOfQuery` was therefore untested.

Add a focused test that runs with `enable_analyzer = 0` and
`query_plan_optimize_prewhere = 0` and checks via `EXPLAIN SYNTAX` that
`FINAL WHERE (k + rand()) % 2 = 0` is not moved to `PREWHERE`, while a
deterministic sorting-key condition still is.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

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

LGTM

The review asked for focused coverage of the new `FunctionCapture::isDeterministic`
override, which is what keeps a filter whose lambda body calls a non-deterministic
function from looking deterministic to consumers that only see the capture node in
the outer `ActionsDAG`.

The new test drives the query condition cache: a `PREWHERE`/`WHERE` filter with
`rand` inside a lambda body must not store granule statistics, while the same
filter with a deterministic body must. Verified by A/B: with the override removed,
the non-deterministic case starts writing an entry to `system.query_condition_cache`
(1 instead of 0), so the test discriminates.
Comment thread src/Functions/FunctionsMiscellaneous.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@novikd novikd self-assigned this Sep 2, 2026
@yariks5s
yariks5s enabled auto-merge September 2, 2026 13:43
@novikd

novikd commented Sep 2, 2026

Copy link
Copy Markdown
Member

There is a related test failure

@yariks5s
yariks5s disabled auto-merge September 2, 2026 13:44
@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

The determinism gate this PR adds is bypassed when the non-deterministic call consumes the lambda argument, so the exact bug the PR fixes survives through constant-folded lambda captures. Verified both ways on this PR's CI binary (head af16b6d, 26.9.1.1):

CREATE TABLE t (k Int32, data String, v UInt64) ENGINE = ReplacingMergeTree(v) ORDER BY k;
INSERT INTO t SELECT number, 'old', 1 FROM numbers(10000);
INSERT INTO t SELECT number, 'new', 2 FROM numbers(10000);
SET optimize_move_to_prewhere_if_final = 1;

SELECT countIf(data = 'old') FROM t FINAL WHERE arrayExists(x -> rand(x) % 2 = 0, [k]);

On the PR binary this still moves to PREWHERE (EXPLAIN actions = 1 shows a Prewhere filter), and the query returns ~2532 rows with data = 'old' that do not exist in the FINAL result (the nested variant arrayExists(x -> arrayExists(y -> rand(y) % 2 = 0, [x]), [k]) leaks ~2593). The cases the PR does fix were re-verified fixed on the same binary: plain rand() on both analyzers, and arrayExists(x -> (x + rand()) % 2 = 0, [k]) (there rand() is argument-independent, the planner hoists it into the outer DAG, and the new recursion sees it as a non-constant child of the capture).

Mechanism: when the only non-deterministic node consumes the lambda argument, it stays inside the captured DAG and all captured children are constants. tryFoldFunctionToConstant (src/Interpreters/ActionsDAG.cpp:581, best-effort re-fold at :895) then executes ExecutableFunctionCapture, whose constant-folding branch returns a ColumnConst wrapping a ColumnFunction — a deferred per-row computation dressed as a constant. The fold is admitted because FunctionCapture::isSuitableForConstantFolding (src/Functions/FunctionsMiscellaneous.h:261) only consults the inner nodes' own isSuitableForConstantFolding, and the random-family functions never override it (default true, src/Functions/IFunction.h:226); plain rand() only escapes top-level folding because its result column is not a ColumnConst. The new gate in isDeterministicExpressionOverSortingKey then skips the folded node entirely: the argument loop does if (argument.isConstant() || ...) continue;, and RPNBuilderTreeNode::isConstant is just column != nullptr (src/Storages/MergeTree/RPNBuilder.cpp:313). The visible DAG confirms it — the filter renders as arrayExists((2, 0), array(k)), so FunctionCapture::isDeterministicInScopeOfQuery never runs.

One correction to the open review thread on this class: the example proposed there, arrayExists(x -> arrayExists(y -> rand() % 2 = 0, [1]), [k]), is NOT moved to PREWHERE on this PR head — rand() never yields a ColumnConst, so nothing in that chain folds and the inner capture stays a visible FUNCTION node that the new recursion rejects. The reachable carrier specifically needs the non-deterministic function to take the lambda argument (or another non-constant local) as input, e.g. rand(x).

Fix direction consistent with existing precedent in the file (non-deterministic SQL-UDF bodies already refuse folding by overriding the flag): extend FunctionCapture::isSuitableForConstantFolding to return false when any inner FUNCTION node is !isDeterministicInScopeOfQuery(). Then rand(x) lambdas stay unfolded and the PR's existing recursion catches them. Alternatively, the gate must not treat a constant that carries a ColumnFunction as a per-row-stable value.

Two adjacent observations from the same verification pass, for completeness: the query condition cache leg is safe even for the folded carrier (the folded COLUMN inherits is_deterministic_constant = false via the non_deterministic_nodes propagation in removeUnusedActions, ActionsDAG.cpp:860-905, and 0 cache entries were observed) — the bypass is specific to the MergeTreeWhereOptimizer gate, which checks arguments through RPNBuilder instead. And a pre-existing sibling on master, untouched by this PR: isNodeDeterministic in src/Processors/QueryPlan/ReadFromMergeTree.cpp:149 (the row-policy-before-FINAL gate at :2993) also inspects only FUNCTION nodes, so a row policy whose condition folds to such a ColumnFunction constant would likewise be applied before FINAL.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
…final-nondeterministic

# Conflicts:
#	src/Functions/FunctionsMiscellaneous.h
@yariks5s
yariks5s added this pull request to the merge queue Sep 18, 2026
Merged via the queue into master with commit 817691f Sep 18, 2026
348 of 351 checks passed
@yariks5s
yariks5s deleted the yarik/fix-prewhere-final-nondeterministic branch September 18, 2026 16:22
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

6 participants