Skip to content

Respect UDF determinism in the AST predicate push-down into distributed subqueries - #119865

Merged
alexey-milovidov merged 8 commits into
masterfrom
fix-legacy-predicate-pushdown-udf-determinism
Sep 27, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
fix-legacy-predicate-pushdown-udf-determinism

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: #117249

ExpressionInfoVisitor decides whether a predicate may be pushed into a subquery. It only consulted FunctionFactory, and user-defined EXECUTABLE and WASM functions are not registered there, so they looked like unknown functions and were treated as deterministic. #117249 fixed the same pattern for the query-plan join disjunctions push-down, and its review pointed out this gap in the AST visitor.

The legacy PredicateExpressionsOptimizer has since been removed from master (7d148af437c3). The remaining user of the visitor is PredicateRewriteVisitor: ReadFromRemote uses it to push a predicate over a column of a distributed subquery into the HAVING of the query it sends to the shard (allow_push_predicate_ast_for_distributed_subqueries). For SELECT count() FROM (SELECT udf(k) AS v FROM remote(...)) WHERE v % 2 = 0, the shard received HAVING v % 2 = 0. That pushed copy calls the function again, so the shard can filter on a different value than the one it returns, even for a non-deterministic UDF.

  • The visitor now resolves user-defined functions through their own factories before FunctionFactory, the same way ActionsVisitor does. For an EXECUTABLE UDF it reads the deterministic flag from the loaded configuration (UserDefinedExecutableFunctionFactory::tryGetIsDeterministic) instead of constructing the function. tryGet with an empty parameters array raises BAD_ARGUMENTS for a UDF that declares command parameters, which would have turned the optimizer walk into a query failure.
  • hasNonRewritableFunction now refuses the rewrite when the subquery's SELECT list contains a non-deterministic function.

A UDF declared deterministic (WASM ... DETERMINISTIC, or <deterministic>true</deterministic> for an EXECUTABLE UDF) is still pushed down. 05260 checks the query text the shard receives. test_executable_user_defined_function covers a parametric, a non-deterministic and a deterministic EXECUTABLE UDF through the same path.

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 AST predicate push-down into distributed subqueries treating non-deterministic EXECUTABLE and WASM user-defined functions as deterministic. It pushed a predicate over such a function's result to the shard, which evaluated the function again.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.840-master (included in 26.10 and later)

…down respects their determinism

`ExpressionInfoVisitor` only consulted `FunctionFactory`, so an `EXECUTABLE` or `WASM` user-defined
function looked like an unknown function and was treated as deterministic. With `enable_analyzer = 0`
and `enable_optimize_predicate_expression = 1`, `PredicateExpressionsOptimizer` then duplicated a
predicate calling a non-`DETERMINISTIC` UDF into the subquery `HAVING` while keeping the outer copy,
evaluating it twice per row and silently dropping rows, the same pattern #117249 fixed for the
query-plan join disjunctions push-down.

Resolve user-defined functions through `UserDefinedExecutableFunctionFactory` and
`UserDefinedWebAssemblyFunctionFactory` first, the way `ActionsVisitor` and `TreeOptimizer` do.

Follow-up to the review of #117249

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f1f9e98]

Summary: ✅


AI Review

Summary

This PR fixes the result-corruption case for non-deterministic EXECUTABLE and WASM UDFs in distributed predicate push-down by teaching ExpressionInfoVisitor about their determinism and by blocking rewrites when a subquery projects a non-deterministic function. The remaining gap is that deterministic EXECUTABLE UDFs are still treated as safe to duplicate, although this rewrite runs them extra times on the shard and changes observable behavior and cost, so I cannot approve it as-is.

Findings

⚠️ Majors

  • [src/Interpreters/ExtractExpressionInfoVisitor.cpp:64] Deterministic EXECUTABLE UDFs are still eligible for predicate push-down even though evaluating them is observable outside the returned value. UserDefinedFunction::executeImpl always runs an external command and increments ExecutableUserDefinedFunction* profile events on every call, so pushing WHERE v ... into shard HAVING duplicates the UDF evaluation per row. That keeps the evaluation-count bug alive for functions like test_function_bash_deterministic: results stay stable, but the shard does extra external work and reports different query metrics.
    Suggested fix: treat EXECUTABLE UDFs as non-rewritable for this pass, or extend ExpressionInfoVisitor / hasNonRewritableFunction to model hasObservableSideEffects and make executable UDFs report it.
Final Verdict

⚠️ Needs changes before merge: the rewrite is still unsafe for deterministic EXECUTABLE UDFs because it can duplicate external executions.

LLVM Coverage Report

Measured on commit f1f9e98.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f1f9e98bcee0e3f283fe090d03f710b9a3ac4b93 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 3 commits September 19, 2026 10:35
…pressionInfoVisitor`

`UserDefinedExecutableFunctionFactory::tryGet` is not non-throwing: it constructs a
`UserDefinedFunction` with an empty `parameters` array, whose constructor raises
`BAD_ARGUMENTS` for a UDF that declares command parameters, such as
`test_function_with_parameter`. That turned a legacy optimizer walk over a predicate
(or over a subquery `SELECT` list, through `hasNonRewritableFunction`) into a query
failure.

`EXECUTABLE` UDFs always report `isDeterministicInScopeOfQuery` as `false` and are not
stateful, so nothing has to be instantiated: use
`UserDefinedExecutableFunctionFactory::has` and mark the expression as
non-deterministic directly. Extend `05212` with the parametric UDF in the outer `WHERE`
and in the subquery `SELECT` list.

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

The analyzer can no longer be disabled by a query since `enable_analyzer` was
deprecated, so the test could not run any more: `--enable_analyzer=0` is refused with
`SETTING_CONSTRAINT_VIOLATION`. `EXPLAIN AST optimize = 1` still runs the old
interpreter, so it remains an entry point into `TreeRewriter` and
`PredicateExpressionsOptimizer`. Assert on the number of occurrences of the function in
the dumped AST: one means the predicate stayed in the outer query, two mean it was
copied into the subquery as well.

Add the parametric executable UDF the review asked for to
`test_executable_user_defined_function`. The stateless configuration has no UDF that
actually declares command parameters - `test_function_with_parameter` puts its
`{param:UInt64}` placeholder in a `command_argument`, and parameters are only extracted
from `command` - while the integration test already ships
`test_function_parameter_python`.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119865&sha=72223ff3247cad9e5bcfe947744ccfd82d022477&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Stress test (arm_msan) hit Logical error: 'Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1. Header: k UInt64, s AggregateFunction(countResample(10, 5, 1), UInt64, UInt64). Chunk: UInt64(size = 100)' (STID 2270-38be) from ISource::prepare. It is unrelated to this pull request, which only changes how ExpressionInfoVisitor resolves user-defined functions, and it is fleet-wide: CIDB shows 69 occurrences of this STID in the last 60 days across ~60 different pull requests and on master (pull_request_number = 0) on 2026-09-14, 2026-09-15, 2026-09-16 and 2026-09-18.

#91602 tracked the same STID and was closed on 2026-02-07, so this is a recurrence and there is no open issue for it.

@groeneai

Copy link
Copy Markdown
Collaborator

Already fixed and merged: #119728, at 04:30 UTC today (5ea18126).

The header names the cause. countResample(10, 5, 1) has begin >= end, and -Resample serializes its nested states with no framing while holding none over an empty range, so the state occupies zero bytes and the state column reads back as zero rows. The chunk then arrives carrying k alone, which is the expected 2 / found 1. #119728 rejects that parameterisation where the function is created (ARGUMENT_OUT_OF_BOUND), so no query can build such a column any more.

Nothing to do on this pull request. The report you linked is from 72223ff3, which is 2741 commits behind that merge commit, and your current head e6f28a8c already contains the fix through the 10:35 UTC master merge.

CIDB agrees so far: all 98 rows of this signature in the last 14 days carry the identical countResample(10, 5, 1) header, across 82 pull requests plus 9 on master and 2 on 26.9, so it has a single cause. Onset was 2026-09-13, 11 to 34 rows a day since, the last at 03:05 UTC today, and nothing in the seven hours since the merge. That is a few hours of evidence rather than proof, so I will keep watching this signature and comment here only if it fires at a head that contains the fix.

One caveat on the two 26.9 rows (2026-09-18, branch tip): #119728 is a backward-incompatible change and carries no backport label, so the signature will remain on that branch unless you want it backported. Since the cause is gone from master, I am not opening a replacement for #91602.

@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Sep 19, 2026
alexey-milovidov and others added 2 commits September 27, 2026 06:39
…ate push-down

`PredicateExpressionsOptimizer` was removed from master by `7d148af437c3`, so the
legacy push-down this PR fixed no longer exists, and `05212` (which reached it via
`EXPLAIN AST optimize = 1`) failed. The remaining user of `ExpressionInfoVisitor`
is `PredicateRewriteVisitor`, which `ReadFromRemote` uses to push a predicate into
the `HAVING` of the query sent to a shard
(`allow_push_predicate_ast_for_distributed_subqueries`).

Two review findings are addressed:

- `hasNonRewritableFunction` ignored `is_deterministic_function`, so
  `SELECT count() FROM (SELECT udf(k) AS v FROM remote(...)) WHERE v % 2 = 0` sent
  `HAVING v % 2 = 0` to the shard even for a non-deterministic UDF, which refers to
  the function once more. It now refuses the rewrite.
- `EXECUTABLE` UDFs were hard-coded as non-deterministic, although the
  configuration has a `deterministic` flag. The new
  `UserDefinedExecutableFunctionFactory::tryGetIsDeterministic` reads it from the
  loaded configuration without constructing `UserDefinedFunction`, so a parametric
  UDF still does not throw `BAD_ARGUMENTS` during the walk.

`05212` is replaced by `05260`, which checks the query text the shard receives, and
the integration test now covers a parametric, a non-deterministic and a
deterministic executable UDF through the same path.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov changed the title Respect UDF determinism in the legacy predicate push-down Respect UDF determinism in the AST predicate push-down into distributed subqueries Sep 27, 2026
/// builds a `UserDefinedFunction` with an empty `parameters` array, and that constructor throws
/// `BAD_ARGUMENTS` for a parametric UDF such as `test_function_parameter_python(1)(k)`, which would
/// turn a mere optimizer walk into a query failure.
if (auto is_deterministic = UserDefinedExecutableFunctionFactory::tryGetIsDeterministic(ast_function.name, data.getContext()))

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.

EXECUTABLE UDFs are still not safe to rewrite based on deterministic alone. UserDefinedFunction::executeImpl always performs external work and increments ExecutableUserDefinedFunction* profile events on every evaluation, so pushing the outer predicate into shard HAVING still duplicates an observable action even when the returned value is stable. For a function like test_function_bash_deterministic, this keeps the evaluation-count bug alive: the shard now runs the child twice per row, once to produce v and once more for HAVING v != ''.

Please keep executable UDFs out of this rewrite (or teach ExpressionInfoVisitor / hasNonRewritableFunction about hasObservableSideEffects) instead of treating deterministic = true as sufficient here.

@clickhouse-gh clickhouse-gh Bot added comp-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 27, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
Merged via the queue into master with commit 645f59a Sep 27, 2026
173 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-legacy-predicate-pushdown-udf-determinism branch September 27, 2026 21:15
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

nickitat added a commit that referenced this pull request Sep 29, 2026
Master PR #119865 made `hasNonRewritableFunction` refuse a
non-deterministic select list as well, so the query shipped to the replicas no longer carries the
condition for `v_nondet_pr_rewrite_shapes` (`rand()`), and the read is `Default`, not `InOrder`. The
condition still reaches the local read as a PREWHERE.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122570&sha=9e0efd96ece0309ec7cee2cde51889e0a90af8ae&name_0=PR
PR: #122570

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-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. 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.

4 participants