Skip to content

Fix text-search functions outside the filter ignoring the text index tokenizer and pre/postprocessor under a WHERE clause - #124092

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:text-index-tokenizer-select-list-under-where
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:text-index-tokenizer-select-list-under-where

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117077
Related: #117774
Related: #116958

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 hasToken, hasAnyTokens, hasAllTokens and hasPhrase outside the filter (for example in the SELECT list) ignoring the text index tokenizer, preprocessor and postprocessor when the query has a WHERE clause, which made the same row return a different result than without WHERE.

Description

On 26.8.18.2, row 2 matches without the WHERE and does not match with it:

CREATE TABLE t (id UInt32, s String, INDEX idx s TYPE text(tokenizer = splitByNonAlpha, postprocessor = lower(s)))
ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, 'xyz'), (2, 'Hello world'), (3, 'foo');
SELECT id, hasAnyTokens(s, 'hello') FROM t ORDER BY id;              -- row 2: 1
SELECT id, hasAnyTokens(s, 'hello') FROM t WHERE id > 0 ORDER BY id; -- row 2: 0

The rewrite that applies the index tokenizer and processors to these functions above ReadFromMergeTree matched the haystack by its name in one step's DAG. With a WHERE, the analyzer's rename of s to __table1.s is in the step below, so the function never matched the index.

#117774 handles part of this by renaming a step's inputs to the scan columns during the rewrite. On master the second query above still returns 0, and SELECT groupArray((id, hasAnyTokens(s, 'hello'))) FROM t WHERE id > 0 now throws NOT_FOUND_COLUMN_IN_BLOCK, because the nodes rebuilt above the function are named after the renamed inputs.

This PR replaces the renaming: the walk composes the DAGs of the steps it passes, and the index match and the preprocessor's haystack check look at each function expressed over the scan's columns.

The test covers the four functions, preprocessor, postprocessor, tokenizer-only, expression, mapValues and Array(String) indexes, PREWHERE, a subquery, ORDER BY, unmerged expressions and a renamed-column negative control. Its ORDER BY id, tuple and preprocessor lines fail on master; the rest pass there since #117774 and guard the replacement. 267 of 268 text-index stateless tests pass locally (the other needs a CI-only server setting).

The AST fuzzer (amd_release, oracle) TLP WHERE mismatch from https://s3.amazonaws.com/clickhouse-test-reports/PRs/118490/38f06bfdb9d5fd15f4cee160f9f89004185a6182/pr/ast_fuzzer_amd_release_oracle/job.log still reproduces on master and is consistent with this PR.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits October 5, 2026 19:21
…nder a WHERE

processAndOptimizeTextIndexFunctions rewrites hasToken, hasAnyTokens,
hasAllTokens and hasPhrase in the Filter/Expression steps above
ReadFromMergeTree with the text index tokenizer and postprocessor. It
analyzed each step's DAG on its own, so the haystack was matched against
the index expression by its step-local name. The analyzer renames the
storage column `s` to `__table1.s` in its first expression; with a WHERE
(a filter or the PREWHERE companion expression), ORDER BY s, a subquery
or query_plan_merge_expressions = 0 that rename lives in a lower step, so
the SELECT-list step saw `INPUT __table1.s`, which never matched the index
column `s`, and the function silently kept the default tokenizer and no
postprocessor. The same row then returned a different value than the
query without WHERE.

The walk now keeps the composition of the Filter/Expression DAGs it has
passed (the current step's inputs expressed over the scan's columns), and
selectConditions analyzes each function merged onto that composition, the
way RPNBuilder names lambda captures. The rewrite itself still edits the
step's own DAG, so headers and output names are unchanged. The first step
above the scan and PREWHERE read the scan directly and are analyzed as
before. A column renamed from a non-indexed one composes to its real
source and is still not matched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `tq where` query is the test's PREWHERE coverage (the next line is the
explicit no-PREWHERE twin), but optimize_move_to_prewhere is randomized and
drawn False in about 5% of runs, in which the line exercised only the
Filter path. Pin optimize_move_to_prewhere and query_plan_optimize_prewhere
on that query so it always covers the PREWHERE plan shape.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
State the dangling-pointer invariant instead of narrating why the DAG is re-read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 1 finding fixed, 2 nits noted
Finding Verdict
⚠️ 05331: the PREWHERE line left optimize_move_to_prewhere to the test runner, which disables it in ~5% of runs, so that line then covered only the filter path Agree, fixed: the line pins optimize_move_to_prewhere = 1, query_plan_optimize_prewhere = 1
💡 No line covers a filter step above the first one (an outer WHERE that cannot be pushed down) Noted: it takes the same code branch as the SELECT-list case
💡 The composed DAG is built for every step walked, even without a text-search function above Noted: plan time only, only for tables with a text index

The re-review of the fix round found nothing new.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Stock settings, 100%: SELECT countIf(hasAnyTokens(s, 'hello')) FROM t WHERE id > 0 returns 0 (1 without WHERE) for a text index with postprocessor = lower(s); same with ngrams(3), lower(s), mapValues(m) and Array(String) indexes. Measured on master and on 26.8.10.6.
b Root cause explained? The steps above ReadFromMergeTree are rewritten one DAG at a time, and the haystack is matched by its step-local name. The analyzer's s -> __table1.s rename sits in a lower step under a WHERE, so the SELECT-list haystack __table1.s never matches the index column s.
c Fix matches root cause? Yes. The walk composes the DAGs it passes, and the index match analyzes the function over the scan's columns. No guard, setting or tag.
d Test intent preserved / new tests added? New 05331_text_index_select_list_under_where: results only, four functions, five index shapes, PREWHERE and filter, subquery, ORDER BY s, unmerged expressions, one renamed-column negative control.
e Both directions demonstrated? Master: every positive line fails. Reverting only the over-scan analysis gives output identical to master. Fix: passes, 50/50 randomized, 50/50 without randomization.
f Fix is general across code paths? All four functions share one decision point. The first step above the scan and PREWHERE read the scan directly and are unchanged; later Filter/Expression steps are composed; row pass-through steps are not.
g Fix generalizes across inputs (params/datatypes/wrappers)? Plain column, expression, mapValues and Array(String) indexes, tokenizer-only and postprocessor indexes; a column renamed from a non-indexed one still gets the default tokenizer. Parallel replicas at both parallel_replicas_local_plan values pass.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; results under WHERE now equal the no-WHERE result.
i Invariants and contracts preserved? Step DAGs and headers change only by the existing rewrite; the composed DAG is a local temporary used for matching; the composition is read from the current step after any replacement. 248/249 text_index tests pass (the other needs the test.hits dataset).

Session id: cron:clickhouse-impl-self-slot-57:20261005-183300

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [305f449]

Summary: ✅


AI Review

Summary

The PR fixes text-search functions outside the scan filter inheriting incomplete text-index semantics under WHERE. Composing the intervening ActionsDAG instances resolves index matching and preprocessor checks against scan columns while preserving step-local names. No actionable findings remain after reviewing the current diff, surrounding implementation, and prior discussion.

Missing context / blind spots
  • ⚠️ Runtime validation used completed PR build 5520424eb4acdda573f3af63ecd3211bce03a97b: 05331_text_index_select_list_under_where matched its reference, and 190 additional cases passed across filters, sorts, subqueries, windows, expression indexes, array indexes, and non-idempotent preprocessing. The composed-DAG implementation is unchanged at reviewed head 305f449ee4f27700867283a6176a4d6db5257590; subsequent upstream changes to input retention were inspected in source. Current-head build and full CI validation remain pending.
Final Verdict

Status: ✅ Approve. No new inline findings to submit.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 5, 2026
@groeneai
groeneai requested review from Ergus and ahmadov October 5, 2026 20:46
@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 Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 305f449ee with master 04eac2ea3 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dff9a1251; 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.

Object file sizes

3 object files changed (-22.48 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp.o 482.77 KiB 460.28 KiB -22.48 KiB (-4.66%)

719 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

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

Job report

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

I think this PR resolves the same bug as #117774. Please wait for the other PR to land first, we can then check if anything is left open.

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Sure, I'll wait for #117774 to land, then rebase on it and check what is left.

For that check: the CI build of #117774's current head (ebea7269, build_amd_binary) still returns [(1,0),(2,0),(3,0)] for the WHERE id > 0 query in the description, same as master; without the WHERE, row 2 is 1. An ngrams(3) index without a postprocessor behaves the same. #117774 changes when the preprocessor is applied; this PR changes how the SELECT-list function's haystack is matched to the index column when a WHERE step sits below it.

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
groeneai and others added 2 commits October 14, 2026 12:43
…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]>
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 groeneai changed the title Fix text-search functions outside the filter ignoring the text index tokenizer and postprocessor when the query has a WHERE clause Fix text-search functions outside the filter ignoring the text index tokenizer and pre/postprocessor under a WHERE clause Oct 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

#117774 has landed, so I merged master and re-checked (master d245b786, which contains it). Two shapes are still wrong there, with the table from the description:

  • SELECT id, hasAnyTokens(s, 'hello') FROM t WHERE id > 0 ORDER BY id still returns 0 for row 2 (1 without the WHERE).
  • SELECT groupArray((id, hasAnyTokens(s, 'hello'))) FROM t WHERE id > 0 now throws NOT_FOUND_COLUMN_IN_BLOCK: Text index: apply the preprocessor wherever the tokenizer applies #117774 renames the step's inputs during the rewrite, and the nodes rebuilt above the function are named after the renamed inputs.

So the PR now replaces that renaming with the composed-DAG lookup, which also feeds the preprocessor's haystack check, and the test gained these shapes. The lines #117774 already fixed stay as a guard for the replacement. The description is updated.

@rschu1ze

Copy link
Copy Markdown
Member

@ahmadov Would you like to check this one?

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Dear @ahmadov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants