Skip to content

Text index: apply the preprocessor wherever the tokenizer applies - #117774

Merged
ahmadov merged 10 commits into
masterfrom
ahmadov/text-index-preprocessor-everywhere
Oct 13, 2026
Merged

ahmadov merged 10 commits into
masterfrom
ahmadov/text-index-preprocessor-everywhere

Conversation

@ahmadov

@ahmadov ahmadov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

The tokenizer and postprocessor were applied to every occurrence of hasToken, hasAllTokens, hasAnyTokens and hasPhrase on an index column, but the preprocessor only to a predicate that skip-index analysis had seen.
Every other occurrence was left with a raw haystack and needle, which matches neither the index definition nor the plain function: the same expression returned different values in WHERE and in the SELECT list of one query, and use_skip_indexes = 0 silently lost rows.

To fix that, we apply the preprocessor to every occurrence, like the tokenizer and the postprocessor, and drop the code that scoped it to the analyzed predicate.

Fixes #117077.

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

Fixed text-index search functions returning wrong results, including silently dropped rows, on a column whose text index declares a preprocessor.


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

Version info

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

The `tokenizer` and `postprocessor` were applied to every occurrence of
`hasToken`, `hasAllTokens`, `hasAnyTokens` and `hasPhrase` on an index
column, but the `preprocessor` only to a predicate that skip-index
analysis had seen.
Every other occurrence was left with a raw haystack and needle,
which matches neither the index definition nor the plain function: the same
expression returned different values in `WHERE` and in the `SELECT` list of
one query, and `use_skip_indexes = 0` silently lost rows.

To fix that, we apply the preprocessor to every occurrence, like the
tokenizer and the postprocessor, and drop the code that scoped it to the
analyzed predicate.

Fixes #117077.
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [de83bdc]

Summary: ✅


AI Review

Summary

This PR fixes the main #117077 symptom by applying the text-index preprocessor on row-scan and SELECT-list paths, and it updates the docs plus the key regression tests. I still see one live correctness blocker in the rewrite selector: when a table has multiple text indexes on the same expression, the inject-only path can bind a function call to the wrong index definition, so the same query can still change semantics depending on hash-map iteration order or on which sibling predicate happened to be analyzed.

Findings

❌ Blockers

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117774#discussion_r4251113403] [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:596] The dismissal assumes “only 1 index per column”, but that invariant is not enforced: MergeTreeIndexText only checks that each text index is single-column (src/Storages/MergeTree/MergeTreeIndexText.cpp:2562), and the query-condition-cache key already has to distinguish “two indexes with the same expression and type but a different name or granularity” (src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:1645). The unconditional rewrite still violates the “row-level evaluation follows the chosen text-index definition” contract on same-expression multi-index tables. collectTextIndexInjectInfos stores every text index in an absl::flat_hash_map (src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:73), then selectConditions resolves collisions by keeping the “first” index for a column (src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:591). That is neither deterministic nor bound to the index-analysis result. If a table defines two text indexes on s with different tokenizer / preprocessor / postprocessor chains, a SELECT-list / use_skip_indexes = 0 / deferred-PREWHERE rewrite can apply the wrong chain and return different results for the same SQL. It can also suppress direct read entirely when an inject-only duplicate wins the iteration order first.
    Suggested fix: either reject inject-only rewriting whenever same-expression text indexes disagree on tokenizer / preprocessor / postprocessor, or thread the exact analyzed index identity through the later rewrite and use only that definition. Please add a focused stateless regression with two text indexes on the same expression and conflicting transforms.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    1. Make same-expression multi-index rewrites deterministic and tied to the intended text-index definition.
    2. Add a regression test that covers conflicting same-expression text indexes on the row-scan and sibling-WHERE paths.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@zlareb1

This comment was marked as low quality.

@rschu1ze

rschu1ze commented Sep 2, 2026

Copy link
Copy Markdown
Member

Proves less code --> less bugs.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit de83bdcef060219f2a1d5799eef0b39f330ce6a2 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ ], "data": [ ], "rows": 0, "exception": "Code: 24…).

See the job log for details.

@ahmadov
ahmadov marked this pull request as ready for review September 3, 2026 08:52
@mintlify

mintlify Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 12, 2026, 6:51 PM

@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 4, 2026
@Ergus

Ergus commented Sep 7, 2026

Copy link
Copy Markdown
Member

I need to read it in detail. The preprocessor was scoped by design because it was susceptible to produce incorrect or ambiguous results

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

There is a problem that this change exacerbates.

Merging a second preprocessor DAG into the same ActionsDAG silently reuses the first one's __lambda node, so one index's preprocessor is applied with another index's lambda.

As ActionsDAG::mergeNodes matches purely by result_name and the DAGs is built by ExpressionAnalyzer/ActionsVisitor, whose lambda capture nodes are named by ActionsMatcher::Data::getUniqueName("__lambda") then the first lambda in every freshly built preprocessor DAG is name __lambda

Suppose an Array index column where a lambda is always generated; then convertASTForIndexColumn wraps the expression in arrayMap(x -> …, col).

Then replace walks every function node of one DAG and each match calls processTextIndexFunction, which merges into the same actions_dag.

This is a pre-existing issue, it reproduces on master. But this PR moves it from "filter DAGs only" to every DAG the walk touches, including SELECT lists, where user lambdas are common.

I would suggest either

  1. Make the preprocessor path name-safe the same way the postprocessor path is (splice via getExpressionAST unconditionally), 2. Rename the preprocessor DAG's nodes to index-qualified names before merging.

/// Preprocessor: only for an index-analyzed predicate in this filter DAG, so it never depends on a sibling filter. Tokenizer/postprocessor also apply on the row-scan path.
const bool apply_preprocessor = is_filter_dag && condition.info->index != nullptr && condition.is_index_analyzed && needApplyPreprocessor(function_name) && preprocessor && preprocessor->hasActions();
/// All three transforms follow the index definition, so they apply to every occurrence of the function.
const bool apply_preprocessor = needApplyPreprocessor(function_name) && preprocessor && preprocessor->hasActions();

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.

Making apply_preprocessor unconditional here changes the row-level semantics whenever a table carries two text indexes on the same expression with different preprocessors. collectTextIndexInjectInfos still feeds inject-only definitions even for use_skip_indexes = 0 / ignore_data_skipping_indices, and selectConditions still resolves same-expression collisions by taking the first index for that column. So SELECT hasAnyTokens(s, 'hello') can now be rewritten either with lower(s) or left raw depending on which same-expression index gets picked, which changes results without any query change.

Can we refuse the inject-only rewrite when the matching same-expression indexes disagree on tokenizer / preprocessor / postprocessor, or otherwise bind the rewrite to the index that skip-index analysis actually selected?

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

Please:

Restore the sibling-WHERE test with expected 10 and add a regression test for the lambda fix. Everything else is OK

/// Preprocessor: only for an index-analyzed predicate in this filter DAG, so it never depends on a sibling filter. Tokenizer/postprocessor also apply on the row-scan path.
const bool apply_preprocessor = is_filter_dag && condition.info->index != nullptr && condition.is_index_analyzed && needApplyPreprocessor(function_name) && preprocessor && preprocessor->hasActions();
/// All three transforms follow the index definition, so they apply to every occurrence of the function.
const bool apply_preprocessor = needApplyPreprocessor(function_name) && preprocessor && preprocessor->hasActions();

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 bot is right, but not a problem for now because we only allow 1 index per column. If that changes, then we will have a problem

actions_dag.project({{expression_name, expression_name}});
actions_dag.removeUnusedActions();

/// Every capture is named `__lambda` and `ActionsDAG::mergeNodes` matches by name, so name captures by content.

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.

We need a test for this. SOmething like (untested):

CREATE TABLE t (a Array(String), b Array(String),
  INDEX ia a TYPE text(tokenizer = splitByNonAlpha, preprocessor = lower(a)),
  INDEX ib b TYPE text(tokenizer = splitByNonAlpha, preprocessor = upper(b)))
  ENGINE = MergeTree ORDER BY tuple();

Select hasAnyTokens(a, 'x'), hasAnyTokens(b, 'X'), arrayMap(x -> x, a) in one SELECT list, with rows that distinguish lower from upper.

SELECT '-- SELECT-list position: preprocessor not applied';
SELECT '-- SELECT-list position: preprocessor applied';

SELECT countIf(hasAnyTokens(s, 'hello')) FROM tab;

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.

This query is one form of #117077: a SELECT-list copy evaluated next to a WHERE that triggers direct read.

Is this working right?

@ahmadov
ahmadov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into master with commit 1bc3dc2 Oct 13, 2026
177 checks passed
@ahmadov
ahmadov deleted the ahmadov/text-index-preprocessor-everywhere branch October 13, 2026 20:44
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 14, 2026
…r-select-list-under-where

Conflict in optimizeDirectReadFromTextIndex.cpp with ClickHouse#117774, which matched a
step's inputs to scan columns by renaming them in place (`source_columns`) for
the duration of the rewrite. Keep this branch's composed-DAG lookup instead and
drop the renaming: it follows alias chains only, and the nodes the rewrite
rebuilds above the function take their names from the renamed inputs, so on
master `SELECT groupArray((id, hasAnyTokens(s, 'hello'))) FROM t WHERE id > 0`
throws NOT_FOUND_COLUMN_IN_BLOCK, and a SELECT-list function above
`ORDER BY id` still keeps the default tokenizer. The composed DAG renames
nothing in the step's DAG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 14, 2026
Since ClickHouse#117774 the preprocessor applies outside the filter too, and its check
that the preprocessor expression contains the haystack compares names. Above
a WHERE the haystack is an input renamed by a step below (`__table1.s`), so
express it over the scan's columns first, like the index lookup does.

Add to 05331 the shapes master still gets wrong after ClickHouse#117774: a SELECT-list
function above `ORDER BY id`, a tuple built over it (throws
NOT_FOUND_COLUMN_IN_BLOCK on master), and a preprocessor index, whose
unmerged-expressions line fails without the haystack change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 11, 2026
`hasToken`, `hasAnyTokens`, `hasAllTokens` and `hasPhrase` on `m['key']`
answered by a text index on `mapValues(m)` got the index tokenizer and
postprocessor in the row-level rewrite, but not its preprocessor: the
rewrite applied the preprocessor only when the haystack is the index
expression itself, which a map element never is. The index stores the
tokens of `f(value)` and prunes by the tokens of `f(needle)`, a necessary
condition only for the preprocessed predicate. For a preprocessor that is
not a per-character map (e.g. the documented `substringIndex(col, '\n', 1)`)
the index skipped rows the raw predicate matched, so the result depended on
`index_granularity`, `use_skip_indexes`, and WHERE vs the SELECT list.

The rewrite now applies the preprocessor of one element to a map element
(`getActionsDAGForElement` / `getElementExpressionAST`, the form
`processConstant` already uses) and preprocesses the needle, as for a
`String` column (ClickHouse#117774).

A key the map does not hold now reads `f(default)` instead of the raw
default. The absent-key guard computes `f(default)` once per condition, in
the constructor so that inject-only conditions agree, and tokenizes it. That
makes the previous conservative "keep every row with a preprocessor" case
exact, and removes `rewrite_only`, whose premise was that the plan does not
preprocess a map element. A preprocessor that raises on the default leaves
such atoms non-pruning; the predicate then raises on a row without the key,
as a `String` column raises on a search term the preprocessor rejects.
`hasToken` gains the guard, and a preprocessed `hasToken` needle with a
separator, on which the function raises, keeps all rows.

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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... 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

5 participants