Repository navigation
Move AI functions to the end of PREWHERE - #117802
Conversation
|
Workflow [PR], commit [23172b5] Summary: ✅
AI ReviewSummaryThe PR postpones expensive AI predicates in automatically generated Final VerdictStatus: ✅ Approve |
|
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).
SELECT count() FROM tab
WHERE flag = 1 AND arrayExists(x -> aiFilter(x, 'matches'), [text])The conjunct's top node is Two fix directions: override 2. The gate is vacuous on the legacy analyzer.
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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units1352 translation units recompiled, 8698 s compile time in total, 1352 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
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
|
|
Please also backport to 26.8 since this is LTS release and baseline for Cloud. |
|
rschu1ze
left a comment
There was a problem hiding this comment.
@george-larionov Can we
- rename
FunctionAIBasetoFunctionAIBaseChat, and - introduce
FunctionAIBaseEmbeddingswhich contains the code shared between aiEmbed and aiSimilarity?
`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]>
589b9eb to
777f538
Compare
Also report it from `FunctionExpression`, which covers constant-folded lambdas. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… 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]>
…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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
The member variable order is viable, good, expensive.
I think we should use the same order here.
There was a problem hiding this comment.
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
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
Backport #117802 to 26.10: Move AI functions to the end of PREWHERE
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]>
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]>
Cherry pick #117802 to 26.9: Move AI functions to the end of PREWHERE
Cherry pick #117802 to 26.8: Move AI functions to the end of PREWHERE
Backport #117802 to 26.9: Move AI functions to the end of PREWHERE
Backport #117802 to 26.8: Move AI functions to the end of PREWHERE
An AI function issues one request per row, and
MergeTreeWhereOptimizerprices 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
isExpensiveis added toIFunction/IFunctionBase, defaulting tofalse. All AI functions set it totrue;FunctionCaptureandFunctionExpressionreport 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.
MergeTreeSplitPrewhereIntoReadStepsgives an expensive condition its own step with filtered input.With
allow_reorder_prewhere_conditions = 0the written order is kept, AI conditions included. An explicit PREWHERE clause is not changed.isExpensivecan also be used by non-AI functions.cc @ayakovlev-clickhouse @rschu1ze
Changelog category (leave one):
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
26.11.1.599-master(included in26.11and later)26.10.2.92,26.9.26.31,26.8.35.29