Skip to content

Supply the text index tokenizer to text-search predicates above a JOIN - #116339

Closed
Ergus wants to merge 13 commits into
ClickHouse:masterfrom
Ergus:Fix_115999_simple
Closed

Ergus wants to merge 13 commits into
ClickHouse:masterfrom
Ergus:Fix_115999_simple

Conversation

@Ergus

@Ergus Ergus commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Closes: #115999
Related: #108808
Related: #113154
Related: #116197

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 hasAnyTokens, hasAllTokens, hasPhrase and hasToken silently returning wrong results on a column with a text index when the predicate cannot be evaluated before a JOIN.

These functions are rewritten during planning to match what the index stores: its tokenizer, preprocessor and postprocessor. #113154 made that rewrite reach steps above the scan, but it stops at a JOIN. A predicate OR-ed with a condition on the other table is evaluated after the join and was left unrewritten, falling back to splitByNonAlpha. With tokenizer = array the index keeps alpha beta gamma as one token while splitByNonAlpha splits it into three, so matching rows disappeared:

SELECT a.record_id
FROM a INNER JOIN b ON a.group_id = b.group_id
WHERE (hasAnyTokens(a.shingle_tokens, ['alpha beta gamma']) AND b.category = 'target')
   OR (hasAnyTokens(a.plain_text, ['fallback']) OR hasAnyTokens(a.shingle_tokens, ['delta epsilon zeta']))
ORDER BY a.record_id;

returned row 2 where rows 1 and 2 match.

The walk now crosses a JOIN and applies the same rewrite beyond it. This also fixes a call in the SELECT list above a JOIN, which returned 0.

Past a join the rewrite is restricted to columns still known to come from the scanned table: the other side can have a column of the same name that the index does not describe. Such a column keeps the default tokenizer, as does a recomputed value (lower(s) AS s, arrayJoin, aggregation). Reading the index directly stays below the join, being a per-granule answer.

Two supporting changes: a column is followed through a step's output header as well as its DAG, since a step can carry it as a pass-through the DAG never mentions; and matching a column to an index ignores the __tableN. prefix added above a join, which is sound only with the restriction above.


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

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b909b10]


AI Review

Summary

This draft extends text-index rewrites past a JOIN by tracking scan-side columns through later steps and by ignoring analyzer-added __tableN. qualifiers when matching an index. The current implementation still leaves several wrong-result cases open, so I do not think it is ready to merge.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:249] trackColumnsThroughStep treats any output-header name match as a pass-through, but ActionsDAG::updateHeader also leaves rewritten outputs with the same name in the header. A post-JOIN step like SELECT lower(s) AS s ... therefore re-adds s to tracked_columns, and a later hasToken(s, ...) is rewritten with the base column's text-index metadata against the recomputed value, returning indexed semantics for the wrong haystack. Suggested fix: derive pass-throughs from matchInputPositionsToHeader(...).passthrough or an equivalent true pass-through mapping instead of every matching output-header name.

  • [src/Storages/MergeTree/MergeTreeIndexConditionText.h:215] The new qualifier normalization only fixes the bare-column case. Expression indexes (lower(__table1.s)), Map carriers (mapKeys(__table1.m), mapValues(__table1.m)), and JSON subcolumns (__table1.json.path) still miss their text index above a JOIN, so those predicates fall back to the default tokenizer and keep returning wrong results. Suggested fix: normalize __tableN. inside the full serialized carrier, or teach each map/JSON helper to strip analyzer qualifiers before comparing against the index header.

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:712] The new tracking map preserves rename information (x -> s), but the rewrite only checks membership and still matches the index against the post-JOIN alias name. After SELECT s AS x ... JOIN ..., hasAnyTokens(x, ...) passes isHaystackTracked() but selectConditions() probes x against the index header, misses the index, and falls back to the default tokenizer. Suggested fix: feed the tracked scan-side name back into MergeTreeIndexConditionText (or rewrite the haystack name before matching) instead of using tracked_columns only as a boolean guard.

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:1180] The post-JOIN inject-only path still drops preprocessor semantics whenever the index came only from collectTextIndexInjectInfos() or the stranded predicate was not part of skip-index analysis. apply_preprocessor is still gated on condition.info->index != nullptr && condition.is_index_analyzed, so TYPE text(tokenizer = splitByNonAlpha, preprocessor = lower(s)) above a JOIN still evaluates hasToken(s, 'hello') against raw HELLO rows and returns 0. Suggested fix: add a preprocessor-capable inject-only rewrite for above-JOIN row-scan evaluation instead of limiting preprocessors to analyzed filter predicates.

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:1204] The new comment says the rewrite now covers the SELECT list, but post-JOIN ExpressionSteps still build the replacer with is_filter_dag = false. That makes apply_preprocessor permanently false there, so SELECT hasToken(val, 'hello') above a JOIN is still wrong for TYPE text(..., preprocessor = lower(val)) unless some postprocessor happens to compensate. Suggested fix: drive the same preprocessor injection for post-JOIN ExpressionSteps and add a focused SELECT-list regression.

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:1272] The new walk still only recognizes JoinStep and JoinStepLogical. Legacy / storage-join plans built as FilledJoinStep hit the else break path here, so a text-search filter stranded above a filled JOIN keeps the original wrong-result behavior. Suggested fix: treat FilledJoinStep as a join boundary too, and only list other physical join step types here if they are actually reachable before this pass runs.

Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b909b101e with master bb113c384 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d469feea5; 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

4 object files changed (+19.18 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp.o 480.26 KiB 498.61 KiB +18.35 KiB (+3.82%)

716 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

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +20.4 s (+7%) in total before that adjustment.

Job report

@Ergus
Ergus force-pushed the Fix_115999_simple branch from 87ffe4a to a842f13 Compare August 26, 2026 21:36
if (step.hasOutputHeader())
{
for (const auto & column : *step.getOutputHeader())
if (auto it = tracked.find(column.name); it != tracked.end())

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.

getOutputHeader() is too coarse to mean "pass-through". ActionsDAG::updateHeader() removes an input column when the DAG produces a new output with the same name, so an ExpressionStep like SELECT lower(s) AS s ... still has s in the output header even though the original scan column is gone. This loop re-adds s to tracked_columns, and a later post-JOIN hasToken(s, ...) is rewritten with the base table's text-index metadata against the recomputed value. The PR description explicitly says recomputed values such as lower(s) AS s must keep the default tokenizer, so this needs to follow only true pass-through inputs (for example via matchInputPositionsToHeader(...).passthrough), not every matching output-header name.

bool hasIndexForColumn(const String & column_name) const { return header.has(column_name) || column_name == normalized_index_column_name; }
bool hasIndexForColumn(const String & column_name) const
{
String unqualified = stripJoinTableQualifier(column_name);

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.

hasIndexForColumn now fixes only the bare-column case. traverseFunctionNode still probes strings like lower(__table1.text), mapKeys(__table1.m) / mapValues(__table1.m), and JSON subcolumns still go through tryMatchNodeToJSONIndex with names like __table1.json.path, so these existing text-index carriers are still unmatched above a JOIN. The new rewrite therefore still falls back to the default tokenizer for expression, Map, and JSON text indexes. The qualifier normalization has to remove analyzer table prefixes inside the full serialized carrier (or in each Map / JSON helper path), not only when the whole string starts with __tableN..


if (!filter_step && !expression_step)
{
if (typeid_cast<const JoinStep *>(step) || typeid_cast<const JoinStepLogical *>(step))

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.

This pass runs in optimizeTreeSecondPass(), after convertLogicalJoinToPhysical() has already turned many joins into physical steps. Lookup joins become FilledJoinStep, and inequality joins become IEJoinStep, but this branch only recognizes JoinStep / JoinStepLogical. For those join implementations the walk still stops at the join, so the original "predicate stranded above the JOIN" wrong-result bug survives unchanged. Please treat the other physical join steps as join boundaries too instead of enumerating only these two types.

if (!need_transform_function && !direct_read_from_text_index)
return replacement;

if (tracked_columns && !isHaystackTracked(function_node, *tracked_columns))

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.

tracked_columns is only used as a membership set here, but trackColumnsThroughStep() preserves more information than that: after a pre-JOIN rename it holds x -> s. A query like

SELECT *
FROM (SELECT s AS x, gid FROM t) AS a
INNER JOIN b ON a.gid = b.gid
WHERE hasAnyTokens(x, ['alpha beta']) OR b.cat = 'x'

still reaches selectConditions() with the haystack serialized as x, so MergeTreeIndexConditionText probes x against the index header and finds nothing. The post-JOIN predicate then falls back to the default tokenizer, which is the same wrong-result hole this PR is trying to close. Please feed the tracked scan-side name back into the matcher instead of using tracked_columns only as a boolean guard.

const String filter_column_name = filter_step ? filter_step->getFilterColumnName() : String{};

TextIndexDAGReplacer replacer(
step_dag, text_index_infos, /*direct_read_from_text_index=*/ false, /*is_filter_dag=*/ filter_step != nullptr,

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.

This new past-JOIN path still does not reproduce text-index preprocessor semantics when the index was discovered only via collectTextIndexInjectInfos() (for example SETTINGS use_skip_indexes = 0, or when the whole predicate stays above the JOIN). processTextIndexFunction() only wraps the haystack when condition.info->index != nullptr, so for TYPE text(tokenizer = splitByNonAlpha, preprocessor = lower(s)) a stranded predicate like hasToken(s, 'hello') OR b.category = 'x' is still executed as raw hasToken(s, 'hello') here and stays wrong for rows containing HELLO. The new comment says this helper applies the same rewrite as below the JOIN, but today it only guarantees tokenizer/postprocessor. It needs a preprocessor-capable inject-only path as well.

@Ergus

Ergus commented Aug 28, 2026

Copy link
Copy Markdown
Member Author

This PR AS IS fixes the issue BUT with the limitation of not working with parallel replicas.

I can solve it with an analyzer pass instead , because ColumnNode names its source table unambiguously, so this needs no __tableN. stripping, no tracked-column set, no row-preserving-step walk and it lands in the query tree, which is what gets shipped to replicas; so parallel replicas, unions and distributed inherit it for free.

I like more that solution because will be simpler and even smaller than this PR. A 3-argument call is invisible to index analysis, so injecting universally trades wrong results for full scans on every text-index query. This is exactly what #115348 will solve.

const String filter_column_name = filter_step ? filter_step->getFilterColumnName() : String{};

TextIndexDAGReplacer replacer(
step_dag, text_index_infos, /*direct_read_from_text_index=*/ false, /*is_filter_dag=*/ filter_step != nullptr,

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.

collectTextIndexInjectInfos() makes the post-JOIN SELECT-list case reachable, but applyTextIndexInjectPastJoin() still constructs the replacer with is_filter_dag = false for every ExpressionStep. processTextIndexFunction() gates apply_preprocessor on is_filter_dag, so a query like SELECT hasToken(p.val, 'hello') above a JOIN on TYPE text(tokenizer = splitByNonAlpha, preprocessor = lower(val)) is still left as the raw two-argument call and returns 0 for HELLO. Please drive the preprocessor injection for post-JOIN ExpressionSteps too, and add a focused SELECT-list regression for a preprocessed index.

@rschu1ze rschu1ze closed this Aug 31, 2026
Ergus added a commit to Ergus/ClickHouse that referenced this pull request Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect results with hasAnyTokens on JOINed table

3 participants