Skip to content

Move AI functions to the end of PREWHERE - #117802

Merged
george-larionov merged 18 commits into
masterfrom
prewhere-do-not-move-ai-functions
Oct 23, 2026
Merged

george-larionov merged 18 commits into
masterfrom
prewhere-do-not-move-ai-functions

Conversation

@george-larionov

@george-larionov george-larionov commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

An AI function issues one request per row, and MergeTreeWhereOptimizer prices a condition only by the size of the columns it reads, so a condition with an AI function could be moved to PREWHERE ahead of cheaper conditions and called on every row read.

A new virtual function isExpensive is added to IFunction / IFunctionBase, defaulting to false. All AI functions set it to true; FunctionCapture and FunctionExpression report it for a lambda whose body is expensive.

A condition containing an expensive function is moved to PREWHERE after all other conditions and is not grouped with other conditions on the same columns. Each PREWHERE read step sees only the rows that passed the previous steps, so the AI function is called only for rows passing the cheaper conditions, and PREWHERE still saves reading the remaining columns for rows it rejects. MergeTreeSplitPrewhereIntoReadSteps gives an expensive condition its own step with filtered input.

With allow_reorder_prewhere_conditions = 0 the written order is kept, AI conditions included. An explicit PREWHERE clause is not changed.

isExpensive can also be used by non-AI functions.

cc @ayakovlev-clickhouse @rschu1ze

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Conditions with AI functions (aiGenerate, aiClassify, aiExtract, aiTranslate, aiFilter, aiRedact, aiEmbed, aiSimilarity) are moved to the end of PREWHERE, so the AI function is called only for rows that pass the cheaper conditions.


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

Version info

  • Merged into: 26.11.1.599-master (included in 26.11 and later)
  • Backported to: 26.10.2.92, 26.9.26.31, 26.8.35.29

@george-larionov
george-larionov marked this pull request as ready for review September 3, 2026 00:05
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23172b5]

Summary: ✅


AI Review

Summary

The PR postpones expensive AI predicates in automatically generated PREWHERE chains and filters intermediate results before evaluating them. The current code addresses the earlier lambda, adaptor, and remaining-WHERE guard findings; preserving order when allow_reorder_prewhere_conditions = 0 is an explicit, documented choice. Focused runtime checks with the PR binary and the new stateless test passed. No actionable findings remain.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 3, 2026
@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

The new gate closes the plain-conjunct case, but two legs stay open at the current head (03c14d7):

1. A lambda-wrapped AI call still moves to PREWHERE (new analyzer, pure defaults).

cannotBeMoved checks isExpensive on the conjunct's own function nodes and recurses via getArgumentAt, which iterates dag_node->children only (src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:849-855 at the PR head). A capture's expression DAG is not among its children, and FunctionCapture does not override isExpensive (no occurrence in src/Functions/FunctionsMiscellaneous.h), so an AI call inside a lambda body is invisible to the gate:

SELECT count() FROM tab
WHERE flag = 1 AND arrayExists(x -> aiFilter(x, 'matches'), [text])

The conjunct's top node is arrayExists (isExpensive = false); its DAG children are the unfolded capture (whose function_base is FunctionCapture, isExpensive = false) and array(text). The aiFilter node lives inside the capture's private expression_actions DAG, which the walk never enters — so the condition stays viable and the AI call is moved to PREWHERE, evaluated once per row read instead of once per surviving row: the same cost bug this PR fixes, persisting in the lambda variant. (The constant-folded variant is not reachable here: all eight AI functions set isSuitableForConstantFolding = false, so an AI-bearing capture never folds to a constant.)

Two fix directions: override FunctionCapture::isExpensive to return true when any function node of the captured DAG is expensive — mirroring the inner-DAG walk isSuitableForConstantFolding already does at FunctionsMiscellaneous.h:261 — which covers every future isExpensive consumer at once; or recurse into capture DAGs in cannotBeMoved, the same shape the pending #109538 adds for its determinism check in this file. A test line with the lambda carrier would pin either choice.

2. The gate is vacuous on the legacy analyzer.

RPNBuilderFunctionTreeNode::getFunctionBase returns nullptr for AST-backed nodes (src/Storages/MergeTree/RPNBuilder.cpp:536-539), so with enable_analyzer = 0 the new function_base && function_base->isExpensive() guard never fires and the PR's own test queries still move the AI call to PREWHERE. If that is an accepted residual, a code comment would help; otherwise the AST leg needs a fallback.

Both legs are cost-only — the gate acts in the fail-safe direction, and AI functions are already non-foldable and marked non-deterministic — so nothing here blocks the PR; flagging so the lambda shape doesn't ship as a blind spot.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 23172b578 with master 69553a30f (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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds an isExpensive trait that only the AI functions set (aiGenerate, aiEmbed, aiSimilarity and the rest). It changes PREWHERE condition order only when a condition contains one of those functions. Neither flagged ClickBench query uses them: Q30 and Q31 filter on SearchPhrase <> '' and then aggregate, so they behave as before. The -11.2% on Q30 is downgraded to not sure, and the suppressed -15.2% on Q31 stays no change. Both PR medians fall inside master's range since the 2026-10-09 baseline shift, which matches the deterministic gates and means the baseline window was small, not that this PR made anything faster.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 240 213 -11.2% <0.0001 aggregation: Q30 has a plain SearchPhrase <> '' filter and no AI functions, so the new expensive-condition ordering never applies. The -11.2% sits inside master's current 200–291 ms range.

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: 54c5bec6-72a4-4176-b05d-2913e1553b5c
  • MIRAI run: d6464c9c-321b-4b56-8c6d-cc4815e50087
  • PR check IDs:
    • clickbench_623676_1791588408
    • clickbench_623682_1791588408
    • clickbench_623688_1791588408
    • tpch_adapted_1_official_623699_1791588408
    • tpch_adapted_1_official_623710_1791588408
    • tpch_adapted_1_official_623746_1791588408

@ayakovlev-clickhouse

Copy link
Copy Markdown
Contributor

Please also backport to 26.8 since this is LTS release and baseline for Cloud.

@george-larionov

Copy link
Copy Markdown
Member Author

@zlareb1

  1. Fixed, good catch.
  2. It takes 2 non-default settings to reach this, and we are phasing out the legacy analyzer AFAIK. I felt it's not worth adding this (extra code always increases risk of bugs, and the "issue" is just a mis-optimization with easy workaround), what do you think?

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@rschu1ze rschu1ze self-assigned this Sep 7, 2026
Comment thread src/Functions/FunctionsMiscellaneous.h Resolved
Comment thread src/Functions/IFunction.h Resolved

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

@george-larionov Can we

  • rename FunctionAIBase to FunctionAIBaseChat, and
  • introduce FunctionAIBaseEmbeddings which contains the code shared between aiEmbed and aiSimilarity?

george-larionov and others added 4 commits October 1, 2026 21:39
`MergeTreeWhereOptimizer` prices a condition by the size of the columns it
reads, so an AI function making one request per row looks nearly free and can
be scheduled ahead of a cheap condition. In PREWHERE it is then evaluated on
every row read instead of only the rows that survive the cheap conditions.

On the 28.7M-row `hackernews` dataset, an `aiFilter` written before a selective
condition on the same column issued a request for all 24.4M comments; it now
issues 21.

Co-Authored-By: Claude Opus 5 <[email protected]>
They derive from `IFunction` directly, so the `FunctionBaseAI` override does
not reach them. The test now lists every AI function, because a new one can
miss the trait the same way.

Co-Authored-By: Claude Opus 5 <[email protected]>
The test asserts the outcome of the WHERE-to-PREWHERE move, and
`clickhouse-test` randomizes `optimize_move_to_prewhere`. The flaky check drew
`False`, so nothing moved and the "cheap condition still moved" column read 0.

Co-Authored-By: Claude Opus 5 <[email protected]>
A capture's DAG is not among the condition's children, so `arrayExists(x ->
aiFilter(x, ...), arr)` was still moved to PREWHERE and evaluated once per row
read. `FunctionCapture` now walks its inner DAG, the same way
`isSuitableForConstantFolding` does.

Co-Authored-By: Claude Opus 5 <[email protected]>
@george-larionov
george-larionov force-pushed the prewhere-do-not-move-ai-functions branch from 589b9eb to 777f538 Compare October 1, 2026 21:41
george-larionov and others added 2 commits October 1, 2026 21:45
Also report it from `FunctionExpression`, which covers constant-folded lambdas.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
george-larionov and others added 2 commits October 2, 2026 17:42
… WHERE

Each PREWHERE step sees only the rows passing the previous ones, so an AI function
is called only for rows passing the cheaper conditions, and PREWHERE still saves
reading the remaining columns.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
With `allow_reorder_prewhere_conditions = 0` an expensive condition is moved to
PREWHERE in the written order. The test reads the final order from `EXPLAIN json = 1`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@george-larionov george-larionov changed the title Do not move AI functions to PREWHERE Move AI functions to the end of PREWHERE Oct 2, 2026
…e-ai-functions

# Conflicts:
#	src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp
#	src/Storages/MergeTree/MergeTreeWhereOptimizer.h
/// Do not move conditions involving all queried columns.
&& info.columns.size() < queried_columns.size();

info.expensive = isExpensiveExpression(conjunct);

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.

isExpensive is only populated on the reorderable analyzeImpl path. In the !allow_reorder_prewhere_conditions branch of analyze, every Condition still leaves expensive = false, so the moved subset is chosen as if an aiFilter(...) conjunct were cheap. With allow_reorder_prewhere_conditions = 0 and move_all_conditions_to_prewhere = 0, that can still auto-move an AI predicate into PREWHERE while the cheaper guard stays in WHERE, bringing back the row-by-row external-call blowup this PR is trying to avoid.

Can we either fill cond.expensive in that branch too and honor it there, or keep expensive conjuncts non-viable when reordering is disabled? The current test pins move_all_conditions_to_prewhere = 1, so it does not cover this setting combination.

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.

This was an explicit decision. I feel that if the user has set allow_reorder_prewhere_conditions=0 they expect that no smart WHERE/PREWHERE optimizations are applied. Note that all the other conditions that are marked non-viable are truly non-viable, not just non-optimal.

auto tuple() const
{
return std::make_tuple(!viable, !good, -min_position_in_primary_key, bytes_per_rejected_row, table_columns.size());
return std::make_tuple(!viable, expensive, !good, -min_position_in_primary_key, bytes_per_rejected_row, table_columns.size());

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.

The member variable order is viable, good, expensive.

I think we should use the same order here.

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.

This order is the correct order: expensive is deliberately placed before good, so an expensive condition is always placed last. I can instead move the member variable order.

…e-ai-functions

# Conflicts:
#	src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp
george-larionov and others added 3 commits October 15, 2026 17:30
A cheap condition that cannot be moved to PREWHERE stays in WHERE, so moving an
expensive condition to PREWHERE would evaluate it first.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…e-ai-functions

# Conflicts:
#	src/Functions/FunctionsMiscellaneous.h
@george-larionov
george-larionov added this pull request to the merge queue Oct 22, 2026
Merged via the queue into master with commit b4499e0 Oct 23, 2026
180 checks passed
@george-larionov
george-larionov deleted the prewhere-do-not-move-ai-functions branch October 23, 2026 00:05
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 23, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 23, 2026
Backport #117802 to 26.10: Move AI functions to the end of PREWHERE
PedroTadim added a commit that referenced this pull request Oct 30, 2026
This branch has no `may_throw` in `MergeTreeSplitPrewhereIntoReadSteps` (from #111954),
no `hasObservableSideEffects` and no `is_runtime_filter`. Keep the split step as it is
here, and port the rest: `isExpensive` for the AI functions and their adaptors, and the
`MergeTreeWhereOptimizer` changes that put expensive conditions in their own group and
move them to PREWHERE after all other conditions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Oct 30, 2026
This branch has no `may_throw` in `MergeTreeSplitPrewhereIntoReadSteps` (from #111954),
no `is_runtime_filter`, and none of the lambda body trait helpers
(`allLambdaBodyFunctions`, `isLambdaBodyStateful` and the others). Keep the split step
as it is here, and port the rest: `isExpensive` for the AI functions and their
adaptors, with a standalone `isLambdaBodyExpensive` for lambdas, and the
`MergeTreeWhereOptimizer` changes that put expensive conditions in their own group and
move them to PREWHERE after all other conditions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Oct 30, 2026
Cherry pick #117802 to 26.9: Move AI functions to the end of PREWHERE
PedroTadim added a commit that referenced this pull request Oct 30, 2026
Cherry pick #117802 to 26.8: Move AI functions to the end of PREWHERE
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 30, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 30, 2026
Backport #117802 to 26.9: Move AI functions to the end of PREWHERE
PedroTadim added a commit that referenced this pull request Oct 30, 2026
Backport #117802 to 26.8: Move AI functions to the end of PREWHERE
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants