Skip to content

Text index: inject tokenizer properly to supported functions outside WHERE/PREWHERE - #113154

Merged
ahmadov merged 17 commits into
masterfrom
ahmadov/text-index-functions-tokenizer-pass
Aug 26, 2026
Merged

ahmadov merged 17 commits into
masterfrom
ahmadov/text-index-functions-tokenizer-pass

Conversation

@ahmadov

@ahmadov ahmadov commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

Resolves #108808

Previously, hasToken/hasAnyTokens/hasAllTokens/hasPhrase functions applied the text index tokenizer/preprocessor/postprocessor only in the WHERE/PREWHERE filter and only when skip-index analysis ran. In the SELECT list, in aggregate arguments, or with use_skip_indexes = 0 they fell back to the default tokenizer, producing results inconsistent with the index path.

The rewrite is now built from the index definition and applied to the Expression/Filter steps above the scan as well.

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):

Inject tokenizer to supported text index functions outside of WHERE/PREWHERE.


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

Version info

  • Backported to: 26.8.1.2016

…de WHERE/PREWHERE

Previously, `hasToken`/`hasAnyTokens`/`hasAllTokens`/`hasPhrase`
functions applied the text index tokenizer/preprocessor/postprocessor
only in the `WHERE`/`PREWHERE` filter and only when skip-index analysis ran.
In the SELECT list, in aggregate arguments, or with `use_skip_indexes = 0`
they fell back to the default tokenizer, producing results inconsistent
with the index path.

The rewrite is now built from the index definition and applied to the
Expression/Filter steps above the scan as well.
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5a3a788]

Summary: ✅


AI Review

Summary

This PR extends text-index rewrite/injection outside WHERE/PREWHERE and fixes several earlier plan-shape gaps, but three supported paths still fall back to the old semantics. The remaining problems are user-visible correctness gaps in the very behavior this Bug Fix claims to make consistent, so this is not ready to merge yet.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:232-246,681-683] A patch part / on-the-fly update on the indexed column still drops the analyzed condition entirely. collectTextIndexReadInfos skips the useful text index as soon as canUseIndex fails, and the fallback entry created by collectTextIndexInjectInfos has info.index == nullptr, so the WHERE rewrite no longer applies the preprocessor. That makes results flip after a lightweight update even though skip-index analysis still uses the predicate on unaffected parts. Keep the analyzed condition_template even when direct read is disabled, and gate only virtual-column creation on direct-read eligibility. Add the focused lightweight-update regression that was previously drafted and then reverted.
  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:1143-1147] The walk still stops at JoinStep, but both planners build the final projection after the join (src/Interpreters/ExpressionAnalyzer.cpp:2139-2144,2265, src/Planner/Planner.cpp:2866-2877). Queries like SELECT hasAnyTokens(t.s, ['foo']) FROM t INNER JOIN u ON t.id = u.id therefore still leave the text-search call above the join and never inject the tokenizer/postprocessor. Either rewrite read-side-only text-search expressions before the join, or continue through join steps when the expression depends only on columns from this ReadFromMergeTree. Add a focused join regression.
  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:1143-1147] ARRAY JOIN is still the same kind of barrier. The old analyzer builds appendArrayJoin before appendSelect (src/Interpreters/ExpressionAnalyzer.cpp:2137,2265), and the new planner inserts ArrayJoinStep before later projection steps (src/Planner/PlannerJoinTree.cpp:3217-3226, src/Planner/Planner.cpp:2869-2877). As a result, countIf(hasAnyTokens(s, ['foo'])) FROM t ARRAY JOIN arr still uses the default tokenizer/postprocessor whenever the text-search call depends only on s and the array join touches something else. Rewrite such expressions before ArrayJoinStep, or traverse it only when the text-search dependencies are disjoint from the array-joined columns, and add a focused regression.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: preserve the analyzed predicate when direct read is disabled by lightweight updates, and cover the missing JOIN and ARRAY JOIN plan shapes so the outside-WHERE behavior is actually consistent on supported queries.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 209/213 (98.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
@ahmadov
ahmadov requested review from Ergus and rschu1ze August 3, 2026 21:08
@rschu1ze

Copy link
Copy Markdown
Member

@Ergus Would you like to review this one - ideally today or tomorrow since it's a bug fix for a user.

SELECT '-- WHERE: preprocessor applied only with use_skip_indexes = 1';

SELECT count() FROM tab WHERE hasAnyTokens(s, 'hello') SETTINGS use_skip_indexes = 0;
SELECT count() FROM tab WHERE hasAnyTokens(s, 'hello') SETTINGS use_skip_indexes = 1;

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.

Looking at the reference these two queries are producing different results... that's what this PR is intended to fix right?

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.

actually this is already an existing index-only-preprocessor behavior: https://fiddle.clickhouse.com/a4d4f696-c26e-46bf-b788-5c1f4b4e2d4b. The PR just adds coverage for both use_skip_indexes on/off values.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5a3a788f1 with master d33f21163 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ab19f7494; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 711.27 MiB 708.23 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

8 object files changed (+40.93 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp.o 440.20 KiB 479.51 KiB +39.31 KiB (+8.93%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@ahmadov
ahmadov requested a review from Ergus August 18, 2026 11:03
const bool apply_preprocessor = is_filter_dag && condition.info->index != nullptr && condition.is_index_analyzed && needApplyPreprocessor(function_name) && preprocessor && preprocessor->hasActions();
const bool apply_tokenizer = needApplyTokenizer(function_name) && tokenizer;
const bool apply_postprocessor = needApplyPostprocessor(function_name) && has_postprocessor;

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.

condition.info->index != nullptr is too strong a gate for the preprocessor now. collectTextIndexReadInfos only fills info.index when MergeTreeDataSelectExecutor::canUseIndex succeeds for the union of updated columns across all queried parts, but the actual skip-index pruning still uses skip_indexes.useful_indices per part and will keep using the analyzed condition on unaffected parts.

That means a single patch part / on-the-fly update can make the whole step fall back to the inject-only entry here, so hasToken / hasAnyTokens / hasAllTokens / hasPhrase stop applying the preprocessor even though the query is still using the text index on other parts. A repro is an index TYPE text(tokenizer = splitByNonAlpha, preprocessor = lower(s)): SELECT count() FROM t WHERE hasToken(s, 'beta') is correct before a lightweight update, then flips back to the raw row-scan result after UPDATE t SET s = s WHERE ... until the patch is merged away.

Can we decouple “this predicate was analyzed by a skip index” from “the index can be direct-read on every queried part”? Preserving the analyzed condition_template even when direct read is disabled, and gating only the virtual-column path on direct-read eligibility, would keep the WHERE rewrite stable. This also needs a focused regression with a patch part / on-the-fly update.

{
if (isRowScanPassThroughStep(step))
continue;
break;

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.

processAndOptimizeTextIndexFunctions still gives up as soon as the path hits a JOIN, but the legacy ExpressionAnalyzer computes the SELECT list only after appendJoin (src/Interpreters/ExpressionAnalyzer.cpp:2127-2133,2252-2253). A query like SELECT hasAnyTokens(t.s, ['foo']) FROM t INNER JOIN u ON t.id = u.id therefore keeps the text-search call above the join, hits this break, and never gets the tokenizer/postprocessor injection. That leaves the advertised outside-WHERE fix query-shape-dependent in a supported path.

Can we either rewrite read-side-only text-search expressions before the join, or keep traversing joins when the expression depends only on columns from this ReadFromMergeTree, and add a focused join regression?

@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
robot-clickhouse added a commit that referenced this pull request Aug 26, 2026
Cherry pick #113154 to 26.8: Text index: inject tokenizer properly to supported functions outside WHERE/PREWHERE
robot-clickhouse added a commit that referenced this pull request Aug 26, 2026
…pported functions outside WHERE/PREWHERE
Ergus added a commit to Ergus/ClickHouse that referenced this pull request Aug 26, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 27, 2026
Backport #113154 to 26.8: Text index: inject tokenizer properly to supported functions outside WHERE/PREWHERE
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 27, 2026
Resolves one conflict in optimizeDirectReadFromTextIndex.cpp selectConditions(),
where ClickHouse#113154 replaced the None-mode branch condition. Strict union: the
canAnswerFunctionNode guard keeps its place ahead of the branch, and the new
is_index_analyzed binding and widened condition are taken unchanged.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 27, 2026
Merging master brings ClickHouse#113154, which applies the index tokenizer, preprocessor
and postprocessor to the row-level evaluation as well, not only to the index
read. Two expectations in this test were written against the earlier behaviour.

The stop-word case asserted that hasAnyTokens for a term the postprocessor maps
to the empty string returns rows when the index is not read. It now returns
nothing in every combination, which is what the two-argument form returns too,
so the parity this test exists to pin still holds and is no longer pinned on a
value where the index and the scan disagreed with each other. Measured on the
merge and on a pre-ClickHouse#113154 master: before, the two-argument form returned no
rows with use_skip_indexes = 1 and two rows with use_skip_indexes = 0; after,
both forms return nothing under either setting. A search for a term the
postprocessor keeps is added next to it, so an empty result there cannot be
mistaken for a table that matches nothing.

The separator-spanning hasPhrase case used use_skip_indexes = 0 to show the
phrase does not occur. The postprocessor is applied on that path now as well,
so the query raises the same BAD_ARGUMENTS as the four assertions above it and
no longer witnesses anything. position() is used instead, which reaches neither
the index nor the postprocessor.
robot-ch-test-poll4 added a commit that referenced this pull request Aug 31, 2026
Cherry pick #113154 to 26.6: Text index: inject tokenizer properly to supported functions outside WHERE/PREWHERE
robot-clickhouse added a commit that referenced this pull request Aug 31, 2026
…pported functions outside WHERE/PREWHERE
robot-clickhouse added a commit that referenced this pull request Aug 31, 2026
Cherry pick #113154 to 26.7: Text index: inject tokenizer properly to supported functions outside WHERE/PREWHERE
robot-clickhouse added a commit that referenced this pull request Aug 31, 2026
…pported functions outside WHERE/PREWHERE
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 31, 2026
PedroTadim added a commit that referenced this pull request Sep 10, 2026
26.6 gained #115586 (`1cc90fa8b08`) after this backport branch was cut, so its
`tryMergeExpressions` block collided with the loop #113154 restructures.

Resolved to master's combined form: hoist the merge into a `walk_begin`
iterator and keep the "parent is not a filter" LOG_TRACE inside the walk. The
resolved `processAndOptimizeTextIndexFunctions` is identical to the one on
master at #113154's merge commit `5c856f8790c`, except for the
`isPrewhereDeferredAfterFinal` arguments, which this backport already omits
because 26.6 has no such method.

The DistinctStep.h include is kept: `isRowScanPassThroughStep` needs it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 10, 2026
… field

The cherry-pick brought master's 7-argument call, but the `deterministic_`
parameter comes from `8493efa7d20` ("Disable the query condition cache for any
non-deterministic virtual column"), which is on 26.8 only -- not on 26.6 or
26.7 -- and is unrelated to #113154. Dropping the argument is behaviour-neutral:
master passes `true`, which is also its default.

  error: no matching constructor for initialization of 'VirtualColumnDescription'
  note: candidate constructor not viable: requires 6 arguments, but 7 were provided

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 10, 2026
26.7 gained #115586 after this backport branch was cut, so its
`tryMergeExpressions` block collided with the loop #113154 restructures.

Resolved to master's combined form: hoist the merge into a `walk_begin`
iterator and keep the "parent is not a filter" LOG_TRACE inside the walk. The
resolved `processAndOptimizeTextIndexFunctions` is identical to the one on
master at #113154's merge commit `5c856f8790c`, except for the
`isPrewhereDeferredAfterFinal` arguments, which this backport already omits
because 26.7 has no such method.

The DistinctStep.h include is kept: `isRowScanPassThroughStep` needs it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 10, 2026
… field

The cherry-pick brought master's 7-argument call, but the `deterministic_`
parameter comes from `8493efa7d20` ("Disable the query condition cache for any
non-deterministic virtual column"), which is on 26.8 only -- not on 26.7 or
26.6 -- and is unrelated to #113154. Dropping the argument is behaviour-neutral:
master passes `true`, which is also its default.

  error: no matching constructor for initialization of 'VirtualColumnDescription'
  note: candidate constructor not viable: requires 6 arguments, but 7 were provided

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
CurtizJ added a commit that referenced this pull request Oct 11, 2026
The backport keeps a `CAST` that drops `Nullable` under the preprocessor, so the
preprocessor output is named after the `CAST` node, e.g.
`lower(CAST(__table1.s, 'String'_String))`. The postprocessor step named its
haystack input with `getNameWithoutAliases`, which rebuilds the name from the
children (`lower(CAST(s, 'String'_String))`), so `mergeNodes` did not reuse the
node and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK` in test
`05340_text_index_preprocessor_cast_drop_nullable`.

Use the `result_name` of the haystack node, as master does since
#113154 (its 26.7 backport is not merged).
This also fixes the same failure for an expression haystack with a postprocessor,
e.g. an index on `concat(s, '')`, which failed on 26.7 before this backport.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=125016&sha=cd400f8bcecb0c83df6515bba43d684b28066d67&name_0=BackportPR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29
PR: #125016

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

6 participants